设置UICollectionViewCell.contentView.translatesAutoresizingMaskIntoConstraints为false后自动布局失效
嘿,我刚好踩过这个坑!问题出在你设置了contentView.translatesAutoresizingMaskIntoConstraints = false这一步上,原因是这样的:
UICollectionViewCell的contentView默认是靠系统的自动遮罩约束(translatesAutoresizingMaskIntoConstraints)来自动适配cell尺寸的,collectionView会自动帮它处理和cell边界的贴合。当你把这个属性改成false之后,contentView本身就失去了确定自己尺寸的约束,它的子视图(也就是你的Button)的四边约束自然也就没有了正确的参考,所以布局就失效了。
下面给你几个解决方案,按推荐程度排序:
最省心的方案:恢复contentView的默认设置
直接删掉cell.contentView.translatesAutoresizingMaskIntoConstraints = false这行代码,让它保持默认的true状态。同时检查一下Storyboard里的Button约束,确保是添加到contentView上的(而不是直接加到cell本身)——拖约束的时候注意选对父视图,一般默认就是contentView,不过保险起见可以确认一下。这样你的Button四边0的约束就能正常生效了。如果确实需要自定义contentView的约束(不推荐)
如果你因为某些特殊需求必须把contentView.translatesAutoresizingMaskIntoConstraints设为false,那一定要给contentView手动添加和cell边界绑定的约束,让它能确定自己的尺寸。代码示例如下:class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var customButton: UIButton! override init(frame: CGRect) { super.init(frame: frame) setupContentViewConstraints() } required init?(coder: NSCoder) { super.init(coder: coder) setupContentViewConstraints() } private func setupContentViewConstraints() { contentView.translatesAutoresizingMaskIntoConstraints = false // 把contentView固定在cell的四个边界上 NSLayoutConstraint.activate([ contentView.topAnchor.constraint(equalTo: self.topAnchor), contentView.leadingAnchor.constraint(equalTo: self.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: self.trailingAnchor), contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) // 这里如果是代码创建Button的话,再添加Button和contentView的约束 // 如果是Storyboard创建的,确保约束已经正确关联到contentView } }
总结一下,99%的情况下你都不需要修改contentView的translatesAutoresizingMaskIntoConstraints属性,保持默认值,专注于子视图和contentView之间的约束就好啦。
内容的提问来源于stack exchange,提问作者younari

