Yeh*_*Ch. 7 constraints uikit ios autolayout swift
我正在尝试以编程方式创建约束以将此粉红色 UIView 居中放置在 UITableViewCell 中。但是,当我添加约束时,它们不适用,并且我在控制台中收到一条消息,指出NSAutoresizingMaskLayoutConstraints无法同时满足某些约束。
因此,当我设置时cell.contentView.translatesAutoresizingMaskIntoConstraints = false,我在控制台中收到此消息:
“不支持更改 UITableViewCell 的 contentView 的 translatesAutoresizingMaskIntoConstraints 属性,这将导致未定义的行为,因为此属性由拥有的 UITableViewCell 管理”。
视图确实居中,但控制台说我不应该更改此属性。
我怎样才能做到这一点?
非常感谢。
UITableViewCell并手动UICollectionViewCell管理它contentView。换句话说,UIKit依赖于单元格的contentViewtranslatesAutoresizingMaskIntoConstraintsTrue因此translatesAutoresizingMaskIntoConstraints不支持更改UITableViewCell 的 contentView的属性,并且将导致未定义的行为。
不要这样做:
cell.contentView.translatesAutoresizingMaskIntoConstraints = false
Run Code Online (Sandbox Code Playgroud)
所以,这是添加UIViewUITableViewCell的完整函数应该是这样的:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5761 次 |
| 最近记录: |