我在为iOS 8+编写代码。
我有一个用作UICollectionView标头的UICollectionReusableView
class UserHeader: UICollectionReusableView {
...
}我的视图集合做了几件事:
在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
}发布于 2017-05-13 16:40:08
我遇到了类似的问题,并通过在视图中使用NSLayoutConstraints来指定标题视图的高度来修复它。然后在视图控制器中配置集合视图的头部:
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
}https://stackoverflow.com/questions/31765677
复制相似问题