UICollectionReusableView标头可能存在错误

时间:2017-01-16 09:17:24

标签: ios swift uicollectionview

我有一个自定义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
}

出于调试原因,我会以不同的颜色显示单元格的边框和内部标签的边框。

以下是发生的情况:单元格获得了正确的框架,但内部标签似乎没有根据其父视图(单元格)更新约束。

在“调试视图层次结构”中,我看到cell.contentView也没有更新自身 - >我想这就是标签不更新的原因。

来自笔尖的牢房:

override func awakeFromNib() {
    super.awakeFromNib()
    self.label.numberOfLines = 0
    self.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    self.translatesAutoresizingMaskIntoConstraints = true
}

2 个答案:

答案 0 :(得分:0)

在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知道你实际上正在使用标题而不是页脚或其他类型的视图类

答案 1 :(得分:0)

问题可能是您正在使用UICollectionViewCell的实例作为补充视图而不是UICollectionReusableView的常用自定义子类。

与UICollectionViewCell不同,

UICollectionReusableView没有contentView属性。后者通过操纵视图层次结构和约束为该属性创建自己的视图。它管理内容视图的框架,并为其提供手势识别器等。单元格(本身就是一个视图)与内容视图(作为单元格的子视图)之间的关系有些不透明,并且在以前版本的iOS中导致developer grief

文档中没有任何内容明确禁止使用UICollectionViewCell作为补充视图。但有迹象表明,预期的做法恰恰相反。

UICollectionViewCell的目的是" present the main content"您的收藏集视图,或" your main data items"。它" 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"提供以下指导:

  

对于补充视图,从对象库中拖动Collection Reusable View并将其放到集合视图中。将视图的自定义类和集合可重用视图标识符设置为适当的值。

没有关于以编程方式配置补充视图的明确指导,但也没有理由认为预期的做法会有所不同。

在测试你的场景(iOS 10.2和iOS 9.3,Xcode 8)时,我无法重现这个问题。我发现内容视图和标签的框架都设置正确。

但对您的问题最简单的解决方案可能是采用预期的做法:

  1. 将FooCollectionViewCell(以及任何关联的nib文件)从UICollectionViewCell的子类更改为UICollectionReusableView的子类。

  2. awakeFromNib删除自动调整遮罩线。