IOS、swift - UICollectionReusableView 不工作

IOS, swift - UICollectionReusableView not working

我想制作 collection 视图 header 但它不起作用。

故事板

在设备上

我下面的代码不工作,打印("ssssss")不显示。

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        print("sssssss")
        switch kind {

        case UICollectionElementKindSectionHeader:

            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                                                             withReuseIdentifier: "mypageheader",
                                                                             for: indexPath) as! MyPageHeaderView
            headerView.backgroundColor = UIColor.blue;
            return headerView

        default:

            assert(false, "Unexpected element kind")
        }
    }

在 viewDidLoad() 上

self.collectionView?.register(MyPageViewController.self,forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,withReuseIdentifier: "mypageheader")

你应该实施 this delegate method:

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

    return CGSize(width: collectionView.bounds.width, height: 100)
}

别忘了在故事板中设置 collectionViewdelegate

如果您通过 .xib/storyboard 配置自定义视图,您不需要在 viewDidload 中添加以下方法:

self.collectionView?.register(MyPageViewController.self,forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,withReuseIdentifier: "mypageheader")

Select 故事板中的视图并转到身份检查器,link Class nad Module

然后转到属性检查器并添加标识符:

并确保在您的代码中添加该方法:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HomeListTopCollectionReusableViewId", for: indexPath) as! HomeListTopCollectionReusableView
  return header
}