UICollectionView AutoSize标题高度

时间:2015-08-01 20:02:05

标签: ios swift uicollectionview

我正在为iOS 8 +编码。

我有一个UICollectionReusableView用作UICollectionView的标题

class UserHeader: UICollectionReusableView {
...
}

My View Collection做了一些事情:

viewDidLoad

中加载NIB
override func viewDidLoad() {
super.viewDidLoad()
resultsCollectionView.registerNib(UINib(nibName: "UserHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "UserHeader")
}

referenceSizeForHeaderInSection中设置标题高度。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSizeMake(0, 500)
}

但是,我的UserHeader视图包含许多UILabel,UIViews在运行时的高度变化,如何指定referenceSizeForHeaderInSection动态的高度?或者,如果我不想在iOS 8+中使用referenceSizeForHeaderInSection进行自动调整大小,请告诉我应该使用的内容。提前谢谢。

为了完整起见,我在这里加载视图,但我不确定这是否与此讨论相关:

func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
    var reusableview:UICollectionReusableView = UICollectionReusableView()
    if (kind == UICollectionElementKindSectionHeader) {
        let userHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "UserHeader", forIndexPath: indexPath) as! UserHeader

                    ... extra code to modify UserHeader

                    reusableview = userHeaderView
    }
    return reusableview
}

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题并通过在视图中使用NSLayoutConstraint来修复它,以指定标题视图的高度。在视图控制器中,我然后配置集合视图的标题:

fileprivate var expectedSectionHeaderFrame = CGRect.zero
let headerIdentifier = "HeaderView"

func calculateHeaderFrame() -> CGRect {
    headerView.setNeedsLayout()
    headerView.layoutIfNeeded()

    let expectedHeaderSize = CGSize(width: view.bounds.width, height: headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)

    return CGRect(origin: .zero, size: expectedHeaderSize)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    expectedSectionHeaderFrame = calculateHeaderFrame()
    return expectedSectionHeaderFrame.size
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    guard kind == UICollectionElementKindSectionHeader else { fatalError("Unexpected kind of supplementary view in (type(of: self))") }

    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath)
    headerView.frame = expectedSectionHeaderFrame

    return headerView
}