首页 > 解决方案 > CollectionView 标头 ReusableView

问题描述

我已经通过storyboard启用了collectionView中的header,然后我编码如下,但是Header没有出现。我想知道有人看到任何问题吗?

AskViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()
    askCollectionView.register(AskCollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "askCollectionViewHeader")
    askCollectionView.delegate = self
    askCollectionView.dataSource = self
}


extension AskViewController : UICollectionViewDelegateFlowLayout, UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
     let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "askCollectionViewHeader", for: indexPath) as! AskCollectionViewHeader
     header.askHeaderTitle.text = "Hi"
     return header
    }

    func collectionView(_ collectionView: UICollectionView,
                      layout collectionViewLayout: UICollectionViewLayout,
                      referenceSizeForHeaderInSection section: Int) -> CGSize{
    
        return CGSize(width: view.frame.size.width, height: 200)
    }
}

AskCollectionViewHeader.swift

import UIKit

class AskCollectionViewHeader : UICollectionReusableView {
    
    @IBOutlet weak var askHeaderTitle: UILabel!
}

标签: swiftcollectionview

解决方案


您正在注册一个类,但没有任何实例化此视图的askHeaderTitle.

使用集合视图标题,您有三个选项:

  1. 在故事板场景中定义可重用视图(通过将“Collection Reusable View”拖到您在 Interface Builder 中设置的集合视图上)。在这种情况下,您将在 IB 中指定类和重用标识符,并且您根本不会调用registerviewDidLoad而是让情节提要来处理。

  2. 在 NIB 中定义可重用视图。在这种情况下,您将在 IB 中注册 NIB,而不是在课程中。

  3. 以编程方式定义可重用视图。只有在这种情况下,您才会register在课堂上使用。但是话又说回来,该子类不会使用@IBOutlet(因为您没有在 IB 中定义它),并且您将以编程方式创建子视图。

我认为选项 1 是最简单的,但显然只适用于使用情节提要和单元原型的情况。如果您计划从多个视图控制器中使用一些可重用的视图,则选项 2 很有用。如果您想手动完成所有操作,选项 3 是一种可能会采用的技术。


推荐阅读