设置 custom UICollectionViewCell.contentview.translatesAutoresizingMaskIntoConstraints = false 后,autolayout 不起作用

After setting custom UICollectionViewCell.contentview.translatesAutoresizingMaskIntoConstraints = false, autolayout is not working

  1. 我在情节提要中创建了一个自定义的 collectionview 单元格。
  2. 我在 collectionview 单元格中添加了一个按钮,并将自动布局 (0,0,0,0) 设置为单元格。
  3. 我制作了一个自定义的 collectionviewcell class。在这个 class,我设置单元格的 contentview.translatesAutoresizingMaskIntoConstraints = false
  4. 单元格按钮的自动布局不工作!

    class SomeCell: UICollectionViewCell {    
       override init(frame: CGRect) {
         super.init(frame: frame)
         self.setup()
       }
    
    
       required init?(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
         self.setup()
       }
    
       func setup() {
         self.contentView.translatesAutoresizingMaskIntoConstraints = false
       }
    
    }
    

code of ViewController

layout in StoryBoard

Simulator: Button's autolayout is missed

我查看了运行时的所有约束,并比较了将 translatesAutoresizingMaskIntoConstraints 设置为 false 和 true 时的情况。
结果是,当 translatesAutoresizingMaskIntoConstraints 设置为 false 时,单元格的内容视图未获得其高度和宽度自动布局约束。在您的情况下,这会导致 ambiguous layout
至于为什么会这样,我猜测 UICollectionFlowLayout 的实现依赖于将 属性 设置为 true,但我找不到任何关于此的文档。

您需要通过重写方法 collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 为委托中的单元格提供大小 https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout/1617708-collectionview

UICollectionView 高度基于精确的帧计算,因此您的约束有问题。您可以在单元格内设置约束,但您需要为单元格提供大小,这与 UITableView 不同。