在尝试以编程方式向UITableViewCell's
contentView添加约束时,我遇到了问题。
在cellForRowAt
中,我以编程方式创建UITextView
,然后尝试应用约束并将其添加到单元格的contentView中。
然而,我得到了崩溃和错误:
The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x1700951d0 UITableViewCellContentView:0x12de3e150.leading == UITextView:0x12e891400.leading + 8 (inactive)>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled.
我的以下代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// Dequeue the cell to load data
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if indexPath.section == 1
{
let textView: UITextView = UITextView()
textView.textColor = UIColor.black
textView.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(textView)
let leadingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 8.0)
let trailingConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -8.0)
cell.contentView.addConstraint(leadingConstraint)
cell.contentView.addConstraint(trailingConstraint)
let topConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: cell.contentView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: textView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)
cell.contentView.addConstraint(topConstraint)
cell.contentView.addConstraint(bottomConstraint)
}
return cell
}
我确实看到了很多关于上述错误的问题,但在应用于UITableViewCell
时没有找到关于此错误的问题。
有人能指出我正确的方向吗?
感谢。
答案 0 :(得分:2)
将textView添加到 cell.contentView (不是单元格)。所以,让我们改为cell.contentView.addSubview(textView)
,它正在发挥作用!