我有一个自定义 UICollectionReusableView
,里面只有一个标签:标签的前导、尾随、顶部和底部约束设置为 8。
在 Controller 上,我注册了单元格,然后:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return self.sectionSizeForIndex(section)
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let cell = self.collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "cellID", forIndexPath: indexPath) as! FooCollectionViewCell
cell.setupLabelWithText("Lorem ipsum")
return cell
}
出于调试原因,我用不同的颜色显示了单元格的边框和内部标签的边框。
发生了什么:单元格得到了正确的框架,但内部标签似乎没有根据其父 View (单元格)更新约束。
在“Debug View Hierarchy”上,我看到 cell.contentView
也不会自行更新 -> 我想这就是标签不更新的原因。
在从 nib 唤醒的单元格中:
override func awakeFromNib() {
super.awakeFromNib()
self.label.numberOfLines = 0
self.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.translatesAutoresizingMaskIntoConstraints = true
}
最佳答案
在 viewForSupplementary 中添加这个
switch kind {
case UICollectionElementKindSectionHeader:
let cell = self.collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "cellID", forIndexPath: indexPath) as! FooCollectionViewCell
cell.setupLabelWithText("Lorem ipsum")
return cell
default: break
}
这会让您的 collectionView 知道您实际上使用的是页眉而不是页脚或其他类型的 View
关于ios - UICollectionReusableView header 可能的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672901/