无法使用自动布局将简单的自动调整大小的集合视图单元格调整为可标注的大小

时间:2019-04-22 03:01:12

标签: ios swift uicollectionview constraints

Xcode 10.2,Swift 5。

我在UICollectionViewCell文件中定义了一个.xib。我将其加载到UIViewController(而不是UICollectionViewController)子类中,并在cellForItemAt中返回它。

在我的UICollectionViewCell(称为TagCell)中,我这样做:

    override
    func
    awakeFromNib()
    {
        super.awakeFromNib()

        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        self.translatesAutoresizingMaskIntoConstraints = false

        self.layer.borderColor = UIColor(red: 0.354, green: 0.442, blue: 0.297, alpha: 0.74).cgColor
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 4.0
    }

笔尖只有我插入的最高级UICollectionViewCell,以及对所有四个边缘具有固定4像素约束的UILabel。我在UILabel中设置cellForItemAt的文本。但是,将使用我在viewDidLoad()中设置的估计高度的所有像元来渲染结果集合:

    override
    func
    viewDidLoad()
    {
        super.viewDidLoad()

        let nib = UINib(nibName: "TagCell", bundle: Bundle(for: type(of: self)))
        self.collectionView.register(nib, forCellWithReuseIdentifier: "TagCell")

        let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.estimatedItemSize = CGSize(width: 60.0, height: 25.0)
}

单元格笔尖文件:

Cell Nib Screenshot

这似乎是我在网上找到的Apple和其他资源所要求的,但我必须缺少一些重要的东西。我还尝试在UILabel上将水平压缩阻力优先级设置为1000,但它们会不断被截断。

我也曾尝试设置>=宽度约束,但这似乎被忽略了。

在设置self.contentView.translatesAutoresizingMaskIntoConstraints之前,我将在调试器中收到约束冲突警告。但是现在它甚至没有抱怨>=宽度限制,甚至认为它违反了它。

1 个答案:

答案 0 :(得分:0)

因此,事实证明您必须在单元格的awakeFromNib()中执行以下操作:

        self.contentView.translatesAutoresizingMaskIntoConstraints = false
        let fixupConsts =
        [
            self.contentView.leftAnchor.constraint(equalTo: self.leftAnchor),
            self.contentView.rightAnchor.constraint(equalTo: self.rightAnchor),
            self.contentView.topAnchor.constraint(equalTo: self.topAnchor),
            self.contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ]
        NSLayoutConstraint.activate(fixupConsts)

尽管WWDC 2014 Session 226非常明确地指出您需要做的唯一事情是将estimatedCellSize设置为非零值,但这根本不够。

如果有人可以提供更好的答案,我会很乐意将其标记为答案。