ios - 使用自动布局的可扩展 UITableView 单元会导致 UIViewAlertForUnsatisfiableConstraints

标签 ios swift uitableview autolayout

我正在尝试使用 UITableViewAutomaticDimension 行高和单元格自动布局的组合来创建可扩展单元格。为了简单起见,我从以下简单的代码开始,我希望它能工作:

import UIKit

class ViewController: UITableViewController {

    let cells = [Cell(), Cell(), Cell()]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50

        for cell in cells {
            cell.tableView = tableView
        }
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return cells[indexPath.row]
    }
}

class Cell: UITableViewCell {

    var cons: NSLayoutConstraint?
    var tableView: UITableView?

    init() {
        super.init(style: .default, reuseIdentifier: nil)

        let button = UIButton()
        contentView.addSubview(button)
        button.addTarget(self, action: #selector(Cell.tapped(_:)), for: .touchUpInside)
        button.setTitle("Press me", for: .normal)
        button.setTitleColor(.red, for: .normal)

        button.translatesAutoresizingMaskIntoConstraints = false

        // constraining the button to the view, so that buttons height would define cell height
        let constraints = [
            button.topAnchor.constraint(equalTo: contentView.topAnchor),
            button.rightAnchor.constraint(equalTo: contentView.rightAnchor),
            button.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
            button.leftAnchor.constraint(equalTo: contentView.leftAnchor),
        ]

        NSLayoutConstraint.activate(constraints)
        cons = button.heightAnchor.constraint(equalToConstant: 100)
        cons?.isActive = true
    }

    func tapped(_ sender: UIButton) {
        // change the height of the button, thus of the contentView too (since the button is constrained to the contentView)
        if cons?.constant == 100 {
            cons?.constant = 200
        } else {
            cons?.constant = 100
        }
        // tell the tableView to redraw itself to apply the change
        tableView?.beginUpdates()
        tableView?.setNeedsDisplay()
        tableView?.endUpdates()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

现在这似乎有效,但是,我仍然收到 UIViewAlertForUnsatisfiableConstraints 警告,并显示以下消息:

(
"<NSLayoutConstraint:0x17408c7b0 V:|-(0)-[UIButton:0x109e10290'Press me']   (active, names: '|':UITableViewCellContentView:0x109e0fd90 )>",
"<NSLayoutConstraint:0x17408c8a0 UIButton:0x109e10290'Press me'.bottom == UITableViewCellContentView:0x109e0fd90.bottom   (active)>",
"<NSLayoutConstraint:0x17408c990 UIButton:0x109e10290'Press me'.height == 200   (active)>",
"<NSLayoutConstraint:0x17408db10 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x109e0fd90.height == 100   (active)>"
)

 Will attempt to recover by breaking constraint 
 <NSLayoutConstraint:0x17408c990 UIButton:0x109e10290'Press me'.height == 200   (active)>

估计的(或当前的)行高似乎与我提供的自动布局约束发生冲突。尽管如此,使用以下代码刷新 tableView 将按预期显示它:

tableView?.beginUpdates()
tableView?.setNeedsDisplay()
tableView?.endUpdates()

如何删除警告?

我知道简单地将高度限制的优先级更改为 999 将删除警告,但在我看来,这是删除它的一种黑客手段,而不是一种解决方案。如果我错了,请解释一下。谢谢。

最佳答案

将高度约束优先级设置为 999 可能感觉就像黑客,但根据 Apple 的文档:

NOTE Don’t feel obligated to use all 1000 priority values. In fact, priorities should general cluster around the system-defined low (250), medium (500), high (750), and required (1000) priorities. You may need to make constraints that are one or two points higher or lower than these values, to help prevent ties. If you’re going much beyond that, you probably want to reexamine your layout’s logic.

可能不太直观:

“我希望按钮高度能够控制单元格高度,因此降低其优先级???”

但是,这似乎确实是“正确”的方法。

引用号:https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/AnatomyofaConstraint.html#//apple_ref/doc/uid/TP40010853-CH9-SW19

关于ios - 使用自动布局的可扩展 UITableView 单元会导致 UIViewAlertForUnsatisfiableConstraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44651241/

相关文章:

ios - 内存管理 iOS 开发应用程序在一些细节项目后不起作用

ios - 从 CLLocationManager 中过滤掉不良位置

objective-c - UIAlertView 显示一次

objective-c - 在 Swift 中实现指针的最佳方式

ios - 避免在进入编辑模式时自动调整 uitableview 单元格内容 View 的大小

ios - UITableView 自定义节标题

ios - 如何更改 iOS 的小数位数?

ios - iTunes Connect 中的 App Store 文件大小警告

ios - 是否可以在 Swift 中连接变量名和字符串/整数?

ios - 在 JWPlayer For iOS 上双击禁用全屏