如何正确编写约束代码

How to properly write the constraint code

我想在 UITableViewCell 中设置一个 UITextView。 在 TableView 函数的一些方法中,我写了下面的代码, 但是它会导致以下错误:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

这是我在 tableView 中的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
    let tableTextView = UITextView()
    tableTextView.translatesAutoresizingMaskIntoConstraints = false
    tableTextView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
    tableTextView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    tableTextView.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
    tableTextView.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
    cell.addSubview(tableTextView)
    return cell
}

首先你应该打电话给:

cell.addSubview(tableTextView)

然后附加约束条件,此外:

All constraints must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view.

所以您的代码可能是:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
    let tableTextView = UITextView()
    cell.addSubView(tableTextView)
    tableTextView.translatesAutoresizingMaskIntoConstraints = false

    tableTextView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
    tableTextView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    tableTextView.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
    tableTextView.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true
    return cell
}

必须在应用约束之前将子视图添加到父视图:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = newTableView.dequeueReusableCell(withIdentifier: "NewCell", for: indexPath) as! NewCellTableViewCell
    let tableTextView = UITextView()
    tableTextView.translatesAutoresizingMaskIntoConstraints = false
    cell.addSubView(tableTextView)
    tableTextView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
    tableTextView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
    tableTextView.widthAnchor.constraint(equalTo: cell.widthAnchor).isActive = true
    tableTextView.heightAnchor.constraint(equalTo: cell.heightAnchor).isActive = true

    return cell
}