ios - UITableViewCell 约束错误

标签 ios swift uitableview

我有一个不同的 UITableViewCells View ,具体取决于其中一个单元格的内容将被加载,但是 1 个单元格让我感到困惑。

我正在尝试将它添加到 TableView 中,但我的约束让我很困惑。将 translatesAutoresizingMaskIntoConstraints 设置为 true 时,它​​显示正常,但是我收到关于约束的众所周知的错误消息。将 translatesAutoresizingMaskIntoConstraints 设置为 false,似乎完全弄乱了布局,尤其是在高度方面。

  class videoCell: UITableViewCell {


       override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
           super.init(style: style, reuseIdentifier: reuseIdentifier)
           playerView()
       }

       required init?(coder aDecoder: NSCoder) {
           fatalError("init(coder:) has not been implemented")
       }

       func playerView() {

            let height = self.frame.width * 9 / 16
            let vpFrame = CGRect(x: 0, y: 0, width: self.frame.width, height: height)
            let vpView = vpView(frame: vpFrame)

            //vpView.translatesAutoresizingMaskIntoConstraints = false
            vpView.sizeToFit()

            addSubview(vpView)

            vpView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
            vpView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true
            vpView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
            vpView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true   

       }

   }

translatesAutoresizingMaskIntoConstraints 错误:

[LayoutConstraints] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want.

我也有一套:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension
}

最佳答案

这里的问题是您混合了基于框架的布局规则和自动布局规则。 基于框架的布局是您在代码中通过计算 vpview 的大小和宽度所做的。 自动布局约束是您通过为位置属性(顶部、底部、左侧、右侧)激活一些 anchor 约束所做的。

默认情况下,当您添加 View 时,会默认解决一些原型(prototype)约束。这就是默认情况下 translatesAutoresizingMaskIntoConstraints 等于 true 的原因。

因此,如果我将您的代码放入您的函数 playerView 中,您就是在对编译器说:

  • 别担心,我会自己计算这个 View 的高度
  • 然后您禁用基于框架的布局,并告诉编译器通过设置 anchor 约束来处理此问题。
  • RESULT => 编译器显然丢失了,因为你计算的尺寸(高度、宽度)和你的 anchor 约束有冲突。

因此,您必须通过自己计算 View 的大小和位置来决定,或者使用自动布局。然后在您的错误控制台上,您可以列出所有冲突的约束并尝试解决它们。

P.S:当你想修复左右 anchor 约束时,一个建议是,你应该更喜欢尾随 anchor 和前导 anchor 。苹果推荐的。进一步了解布局和自动布局的 Apple 文档:Apple doc

关于ios - UITableViewCell 约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46491368/

相关文章:

ios - NSURLConnection 使异步调用 aSync 并处理自签名证书

iOS/objective-C : Swipe to Left causing crash in tableview created with code

swift - UIActivityViewController - 不能同时 AirDrop 多个对象类型

ios - TableView圆角和阴影

ios - subview 相对于父 View 的父 View 的坐标

ios - 我是否需要将隐私 "purpose string"添加到我的应用程序的 Info.plist 以允许它在 iOS 10 上运行?

ios - Swift - 在 UIPageViewController 中的 3 个不同 View Controller 之间导航按钮

ios - 当值为空字符串时,TextField 不显示底线 Material Swift

ios - 当我滚动 UiTableView 时,TextLabel 颜色自动改变

ios - 在uitableviewcell中异步加载图像