我有一个自定义的UICollectionReusableView,里面只有一个标签:标签的前导、尾随、顶部和底部约束设置为8。
在控制器上,我注册了单元,然后:
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
}出于调试的原因,我用不同的颜色显示了单元格的边框和内部标签的边框。
结果如下:单元格获得了正确的框架,但内部标签似乎没有根据其父视图(单元格)更新约束。
在"Debug View Hierarchy“中,我看到cell.contentView不会自动更新->,我想这就是为什么标签不会更新的原因。
在从nib唤醒的细胞中:
override func awakeFromNib() {
super.awakeFromNib()
self.label.numberOfLines = 0
self.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.translatesAutoresizingMaskIntoConstraints = true
}发布于 2017-01-16 17:56:14
在viewForSuplementary中添加此内容
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知道您实际使用的是页眉,而不是页脚或其他类型的视图类型
发布于 2017-01-18 11:38:19
问题可能是,您正在使用UICollectionViewCell的一个实例作为补充视图,而不是使用通常的UICollectionReusableView自定义子类。
与UICollectionViewCell不同,UICollectionReusableView没有contentView属性。后者通过操作视图层次结构和约束为该属性创建自己的视图。它管理内容视图的框架,并为其提供一个手势识别器,等等。单元格(本身就是一个视图)和内容视图(作为单元格的子视图)之间的关系有些不透明,这导致了以前版本的iOS中的developer grief。
文档中没有明确禁止使用UICollectionViewCell作为补充视图。但有隐含的迹象表明,预期的做法是相反的。
UICollectionViewCell的目的是"present the main content“您的集合视图,或"your main data items”。It "presents the content for a single data item“。补充意见,另一方面,"are separate from the collection view's cells“。"Like cells, these views are provided by the data source object, but their purpose is to enhance the main content of your app.“
在故事板中配置补充视图时,"Collection View Programming Guide for iOS“提供了以下指导:
对于补充视图,请将集合可重用视图从对象库中拖放到集合视图中。将视图的自定义类和集合可重用视图标识符设置为适当的值。
没有关于以编程方式配置补充视图的明确指导,但也没有理由认为预期的实践会有任何不同。
在测试您的场景(Xcode10.2和iOS 9.3,Xcode8)时,我无法重现这个问题。我发现内容视图和标签的框架都设置正确。
但是对你的问题最简单的解决方案可能是采用预期的做法:
从awakeFromNib.中自动调整遮罩线的大小,将
https://stackoverflow.com/questions/41672901
复制相似问题