【问题标题】:AutoLayout in UITableViewCell contentViewUITableViewCell contentView 中的自动布局
【发布时间】:2018-12-03 21:29:03
【问题描述】:

我正在尝试以编程方式创建约束以将这个粉红色 UIView 居中在 UITableViewCell 中。但是,当我添加约束时,它们不适用,并且我在控制台中收到一条消息,指出某些 NSAutoresizingMaskLayoutConstraints 不能同时得到满足。

所以当我设置cell.contentView.translatesAutoresizingMaskIntoConstraints = false 时,我会在控制台中收到这条消息:

“不支持更改 UITableViewCell 的 contentView 的 translatesAutoresizingMaskIntoConstraints 属性,这将导致未定义的行为,因为此属性由拥有的 UITableViewCell 管理”。

视图确实居中,但控制台说我不应该更改此属性。

我怎样才能做到这一点?

Before setting the property to false

After setting the property to false

非常感谢。

【问题讨论】:

  • 你能显示你的约束创建代码吗?
  • 还要确保约束不会因单元重用而重复。您可能会添加两次或更多相同的约束。我还建议不要对表格视图单元格进行动态约束,您可能会在那里遇到性能问题。

标签: ios swift autolayout uikit constraints


【解决方案1】:

UITableViewCellUICollectionViewCell 手动管理其 contentView。换句话说,UIKit 依赖于单元格的 contentView,其 translatesAutoresizingMaskIntoConstraints 为 True,因此不支持更改 UITableViewCell 的 contentView 的 translatesAutoresizingMaskIntoConstraints 属性,这将导致未定义的行为。

不要这样做:

cell.contentView.translatesAutoresizingMaskIntoConstraints = false

因此,在 UITableViewCell 中添加 UIView 的完整函数应该如下所示:

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
}

【讨论】:

  • 非常感谢!我什至不知道这个 .constraint 存在
【解决方案2】:

另外,请确保在单元格的 xib 中,应选择布局

“自动调整大小蒙版”

而不是“推断(自动调整蒙版)”

如图所示

【讨论】:

  • 这应该是正确的解决方案,谢谢@Ghulam Rasool
  • 这个答案节省了我的时间,谢谢!
  • 这就是我的答案。
【解决方案3】:

您不需要将translatesAutoresizingMaskIntoConstraints = false 设置为表格视图单元格的contentView

您只需将translatesAutoresizingMaskIntoConstraints = false设置为动态添加的视图,默认为IBOutletstranslatesAutoresizingMaskIntoConstraints = false

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    相关资源
    最近更新 更多