我正在为 iOS 8+ 编写代码。
我有一个 UICollectionReusableView
用作 UICollectionView
的标题
class UserHeader: UICollectionReusableView {
...
}
我的 View 集合做了一些事情:
在 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
View 由许多 UILabel、UIView 组成,它们的高度在运行时发生变化,我如何为动态的 referenceSizeForHeaderInSection
指定高度?或者,如果我不应该使用 referenceSizeForHeaderInSection
在 iOS 8+ 中自动调整大小,请告诉我应该使用什么。提前致谢。
为了完整起见,这是我加载 View 的方式,但我不确定这是否与此讨论相关:
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
}
最佳答案
我遇到了类似的问题并通过在 View 中使用 NSLayoutConstraint
来指定标题 View 的高度来修复它。然后在 View Controller 中配置 Collection View 的 header :
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
}
关于ios - UICollectionView AutoSize 标题高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765677/