ios - 引用 UICollectionView header 补充 View 的更简洁、更不脆弱的方式

标签 ios swift uicollectionview

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

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
        }
    }

}

那个 getter 看起来特别长,而且看起来也很脆弱。

有没有更简洁的方法来引用标题补充 View ?或者这是唯一的方法?

有什么方法可以利用出队机制来存储它(因为我已经在检索它了?)

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
}

最佳答案

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

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

关于ios - 引用 UICollectionView header 补充 View 的更简洁、更不脆弱的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947365/

相关文章:

ios - 当 UIDeviceOrientationDidChangeNotification 在 UIView 中捕获时,UIInterfaceOrientation 尚未更新

swift - 如何加载单例类属性?

ios - 为什么主视图没有在自定义交叉溶解转场中与 View Controller 对齐?

SwiftUI:如何自定义仅适用于 iPad 的工作表?

ios - 添加数据并在关闭 ImagePicker 后重新加载 CollectionView - Swift - iOS

ios - iPhone串口编程

iphone - 如何呈现 tabview Controller ?

ios - 在一个屏幕上有一些 UITableViews 和一些 UICollectionViews

javascript - 无法将 base64 图像从 WKWebView 发送到页面上的 JavaScript

iOS swift : Fatal error with unwrapping optional in UICollectionView