UICollectionView header dynamic height using Auto Layout

后端 未结 5 1074
臣服心动
臣服心动 2020-11-30 02:45

I have a UICollectionView with a header of type UICollectionReusableView.

In it, I have a label whose length varies by user input.

5条回答
  •  自闭症患者
    2020-11-30 03:15

    @Pim's answer worked for me but as @linus_hologram in the comment section mentioned this solution makes AutoLayout complain about unsatisfiable constraints. I found a simple workaround:

    In collectionView(_:layout:referenceSizeForHeaderInSection:) instead of getting a reference to the view that your instance of UICollectionView wants to reuse using collectionView(_:viewForSupplementaryElementOfKind:at:) just create an instance of your header view class on the fly and add a width constraint so that AutoLayout will be able to calculate your header's width:

    let headerView = YourCustomHeaderClass() 
    headerView.translatesAutoresizingMaskIntoConstraints = false
    headerView.widthAnchor.constraint(equalToConstant: collectionView.frame.width).isActive = true
    let size headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
                        return size
    return size
    

提交回复
热议问题