我试图以编程的方式创建约束,将这个粉红色的UIView放在一个UITableViewCell中。但是,当我添加约束时,它们不适用,我在控制台中得到一条消息,其中说某些NSAutoresizingMaskLayoutConstraints不能同时满足。
因此,当我设置cell.contentView.translatesAutoresizingMaskIntoConstraints = false时,我在控制台中得到以下消息:
“不支持更改contentView的contentView属性,这将导致未定义的行为,因为该属性由拥有的UITableViewCell管理”。
视图确实居中,但是控制台说我不应该更改这个属性。
我怎样才能做到这一点?
非常感谢。
发布于 2018-06-25 10:54:28
UITableViewCell和UICollectionViewCell手动管理其contentView。换句话说,UIKit依赖于具有translatesAutoresizingMaskIntoConstraints为True的单元格的contentView,因此不支持更改UITableViewCell的contentView的translatesAutoresizingMaskIntoConstraints属性,这将导致未定义的行为。
别这么做:
cell.contentView.translatesAutoresizingMaskIntoConstraints = false因此,将UIView添加到UITableViewCell中的完整函数如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
//if already added the subview?
if cell.contentView.subviews.count == 0 {
let view = UIView() //your pinkView
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = UIColor.purple
cell.contentView.addSubview(view)
view.centerXAnchor.constraint(equalTo: cell.contentView.centerXAnchor).isActive = true
view.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor).isActive = true
view.widthAnchor.constraint(equalToConstant: 50.0).isActive = true
view.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
}
return cell
}发布于 2021-09-23 09:55:33
此外,请确保在单元格的xib中,布局应被选择为
“自动调整面罩”
而非“推断(自动调整掩蔽)”
如图所示

发布于 2018-06-25 10:39:26
您不需要将translatesAutoresizingMaskIntoConstraints = false设置为tableview单元格的contentView。
您只需要将translatesAutoresizingMaskIntoConstraints = false设置为动态添加的视图,默认情况下设置为IBOutlets translatesAutoresizingMaskIntoConstraints = false。
https://stackoverflow.com/questions/51021203
复制相似问题