更清晰,更不易碎的方式来引用UICollectionView标头补充视图

时间:2017-12-22 21:03:47

标签: ios swift uicollectionview

目前我在我的UICollectionViewController子类中引用了一个UICollectionView标头,如下所示:

class HeaderCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register header view XIB
        collectionView?.register(UINib(nibName: headerNibName, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseIdentifier)

        // Configure header view height
        headerView?.height = HeaderViewHeight(
            origin: 250.0,
            max: UIScreen.main.bounds.height
        )

    }

    var headerView: HeaderView? {
        // Convenience getter for HeaderView
        get {
            guard let headerView = collectionView?.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(row: 0, section: 0)) as? HeaderView else { return nil }
            return headerView
        }
    }

}

这个吸气者看起来非常漫长,而且看起来也很脆弱。

是否有更清晰的方式来引用标题补充视图?或者这是唯一的方法吗?

我是否有某种方法可以利用出列机制来存储它(因为我已经检索它了?)

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let headerView: HeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseIdentifier, for: indexPath) as! HeaderView
    return headerView
}

1 个答案:

答案 0 :(得分:1)

您可以摆脱使用headerView作为计算属性,只需为HeaderView方法中创建的viewForSupplementaryElementOfKind分配即可。如果您只需要配置其高度,则可以使用UICollectionViewDelegateFlowLayout方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(
        width: collectionView?.bounds.width,
        height: someHeaderViewHeight
    )
}
相关问题