【问题标题】:Header Section not displaying in collection view programatically标题部分未以编程方式显示在集合视图中
【发布时间】:2017-12-15 19:45:55
【问题描述】:

这是我的代码

import UIKit

class UserProfileController : UICollectionViewController, UICollectionViewDelegateFlowLayout{

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = .white

        //NEED TO UPDATE: GET USERNAME TO AND SET NAVTITLE
        fetchUser()

        //UPDATE ALL USER PAGE INFO IN

        collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
    }

    fileprivate func fetchUser(){
        //Assumed loged in get user ID
        //guard let uid = currentUser?.uid else {return}

        //NEED TO UPDATE: GET USERNAME FROM USER ID HASH
        let username = "User Profile"
        navigationItem.title = username
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath)

        header.backgroundColor = .green

        return header
    }

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

这一切在我看来都不错,但我不确定这里出了什么问题。

【问题讨论】:

  • 您是否覆盖了UICollectionViewDataSourcenumberOfSections 函数?你有没有实现过这个协议?因为除非给集合视图一些数据,否则你什么都看不到。
  • 我重写了这个函数,没有任何反应

标签: ios swift uicollectionview uicollectionviewdelegateflowlayout


【解决方案1】:

您发布的代码似乎没有任何问题。也许你的故事板有问题?

【讨论】:

  • 我确实收到了一个警告,我曾经使用 main.storyboard 但后来我切换到以编程方式执行所有操作,所以故事板是空的,每次我运行时都会得到:无法实例化默认值UIMainStoryboardFile 'Main' 的视图控制器 - 也许未设置指定的入口点?
  • 我可以看到集合视图,如果我将它的背景设置为红色,屏幕是红色的,所以我知道它在那里,但标题不会显示
  • 你是如何让它显示的?我重新创建了我的项目来测试它,但仍然无法让它出现。你做的时候有没有改过???
  • 我逐字复制/粘贴了您的代码。我从一个新项目开始,在故事板中创建了一个导航控制器,并在它的根视图控制器中创建了一个集合视图控制器。我将新集合视图控制器的类设置为“ViewController”并将您的代码粘贴到该类中。没有额外的方法或代码。
  • 无论是什么问题,都不在您输入问题的代码中。
猜你喜欢
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多