如何正确编写约束代码

问题描述 投票:1回答:2

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

由于未捕获的异常'NSGenericException'而终止应用程序,原因:'无法使用锚点激活约束,因为它们没有共同的祖先。约束或其锚点是否引用不同视图层次结构中的项目?这是非法的。

这是我在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
}
swift xcode swift4 xcode9
2个回答
1
投票

首先你应该打电话:

cell.addSubview(tableTextView)

然后附加约束,而且:

所有约束必须仅涉及接收视图范围内的视图。具体而言,涉及的任何视图必须是接收视图本身或接收视图的子视图。

所以你的代码可能是:

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
}

0
投票

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.