自动调整UICollectionView标头的大小

Kel*_*Lau 6 ios uicollectionview uicollectionreusableview swift

我正在尝试为待办事项列表类型的应用制作详细屏幕。这是详细信息屏幕当前的外观:

详细画面

这是UICollectionViewController带有标题的。标头包含2个UILabel对象和1个UITextView对象。这些对象的布局由垂直管理UIStackView。A UIView用于设置白色背景。

我在定义UICollectionReusableView运行时的高度时遇到一些困难。任何建议表示赞赏。

Mic*_*ael 0

以下是如何在没有 XIB 文件的情况下使用自动布局处理自定义 UICollectionViewReusableView 的方法。

  1. 实现referenceSizeForHeaderInSection委托方法。
  2. 在其中,实例化用作标题视图的视图。
  3. 将其可见性设置为隐藏,以避免闪烁。
  4. 将视图添加到集合视图的超级视图中。
  5. 使用自动布局设置其布局,以匹配标题的预期视觉结果。
  6. 调用setNeedsLayoutlayoutIfNeeded
  7. 从超级视图中删除视图

注意:我不太喜欢这个解决方案,因为它每次都会将自定义视图添加到 CollectionView 的超级视图中,以执行计算。但我没有注意到任何性能问题。

注意#2:我会将其视为临时解决方案,并在发布后迁移到自动调整大小的补充视图。

我使用PureLayout来实现自动布局。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

    let header = CustomHeaderView()

        header.isHidden = true;
        self.view.addSubview(header)
        header.autoPinEdge(toSuperviewEdge: .leading)
        header.autoPinEdge(toSuperviewEdge: .trailing)
        header.autoPin(toTopLayoutGuideOf: self, withInset: 0)
        header.setupHeader(withData: self.data)
        header.setNeedsLayout()
        header.layoutIfNeeded()
        header.removeFromSuperview()

        return header.frame.size
}
Run Code Online (Sandbox Code Playgroud)