【问题标题】:IOS, swift - UICollectionReusableView not workingIOS,swift - UICollectionReusableView 不工作
【发布时间】:2023-03-15 01:21:01
【问题描述】:

我想制作集合视图标题,但它不起作用。

故事板

在设备上

我下面的代码不起作用,print("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")

【问题讨论】:

  • 你不应该改用register(MyPageHeaderView.self;...吗?
  • 是的,他应该... :)

标签: ios iphone swift xcode9


【解决方案1】:

你应该实现this delegate method:

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

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

不要忘记在情节提要中设置collectionViewdelegate

【讨论】:

  • @이예린,您是否将collectionViewdelegate 出口设置为ViewController
  • 是的,并实现 UICollectionViewDelegateFlowLayout。不能调用这个方法 ((override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView ))
  • @이예린,请在我的回答中的referenceSizeForHeaderInSection 方法中放置一个断点,并告诉我它是否被调用。
  • 我使用的是开源软件,但 'referenceSizeForHeaderInSection' 函数的定义不同。谢谢。!!!
【解决方案2】:

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

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

选择情节提要中的视图并转到身份检查器,然后链接ClassModule

然后去属性检查器和标识符:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2020-05-18
    • 2018-12-06
    • 2018-06-15
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多