目前我正在我的 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/