iOS CollectionView header 不显示

标签 ios uicollectionview swift3

我试图将分段控件添加到我的页眉上,但我在执行此操作时遇到了问题。在这个例子中,为了让事情更简单,我添加了一个标签,但它也没有显示。有人能告诉我为什么这没有发生吗?

import UIKit

class SessionsViewController: UICollectionViewController , UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        prepareCollectionView()

        view.backgroundColor = UIColor.white
        navigationController?.navigationBar.isTranslucent = true

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Log Out", style: .plain, target: self, action: #selector(handleLogout))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "plus") , style: .plain, target: self, action: nil)
        navigationItem.rightBarButtonItem?.tintColor = UIColor.honePalette.accent
    }


    func prepareSegmentedControll()->UISegmentedControl{
        let items = ["Future Sessions", "Past Sessions"]
        let control = UISegmentedControl(items: items)
        control.selectedSegmentIndex = 0
        control.tintColor = UIColor.honePalette.accent

        let font = UIFont.systemFont(ofSize: 12)
        control.setTitleTextAttributes([NSFontAttributeName: font], for: .normal)
        return control
    }

    func prepareCollectionView(){
        collectionView?.backgroundColor = UIColor.white
        collectionView?.alwaysBounceVertical = true
        collectionView?.register(sessionsInfo.self, forCellWithReuseIdentifier: "cellId")
    }

    // return of the number per item per section
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    //this is when the collection is clicked
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let indexPath = collectionView.indexPathsForSelectedItems
        print("this is index path:", indexPath)

    }

    // this is the cell of the collection returning initialized with the SessionsInfo
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as? sessionsInfo
        myCell?.sessionLabel.text = "cell  \(indexPath.row)"
        return myCell!
    }
    // this is when the size of the cell returns
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width - 10, height: 80)
    }

    // return supplementary view
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {



        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)

        let label = UILabel(frame: headerView.bounds)
        label.text = "Top View"
        label.font = UIFont(name: "helvetica", size: 12)
        label.textAlignment = .center
        headerView.addSubview(label)
        //headerView.headerLabel.text = "header"

        return headerView


    }


    func handleLogout(){
        BaseServices.baseServices.signOut()
        present(LoginViewController(), animated: true, completion: nil)

    }
}


class headerInfo : UICollectionReusableView{
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupHeader()
    }

    var headerLabel : UILabel = {
        let label = UILabel()
        label.text = "HEADER"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupHeader(){

        backgroundColor = UIColor.honePalette.raindrops
        addSubview(headerLabel)
        addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":headerLabel]))
        addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":headerLabel]))

    }

}


class sessionsInfo: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSessions()
    }

    var sessionLabel : UILabel = {
        let label = UILabel()
        label.text = "sessionView"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    var sessionTimeLabel : UILabel = {
        let label = UILabel()
        label.text = ""
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    var sessionLocationLabel : UILabel = {
        let label = UILabel()
        label.text = ""
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    func setupSessions(){

        backgroundColor = UIColor.honePalette.raindrops
        addSubview(sessionLabel)
        addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":sessionLabel]))
        addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":sessionLabel]))

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



}

最佳答案

我在新项目中尝试了您的代码,但您遗漏了两个关键步骤:注册补充 View 和设置标题大小。

在您的prepareCollectionView 函数中,您还需要注册标题 View :

collectionView?.register(headerInfo.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")

您还需要实现另一个提供标题 View 大小的委托(delegate)函数:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: 100, height: 100) // fix to be your intended size
}

这是它有效的证明。 (我无法访问您的自定义颜色,这就是为什么一切都是橙色和灰色的原因。)

collection view header screenshot

关于iOS CollectionView header 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936731/

相关文章:

ios - Xcode 8 : Archive build fails (for nested frameworks) with link errors. 常规构建编译成功

ios - 如何使 subview 的一部分从 super View 突出时不可见?

ios - 尝试与 Opengl 纹理共享 Metal 纹理

ios - 如何在 UIView 中动态添加/删除按钮并重新定位其下方的按钮并垂直调整 View 大小?

swift - 不同数据的两个 Collection View 还是一个?

ios - 为什么当我返回时我的主视图 Controller 不更新?

ios - 通过 UICollectionView 的高度设置 UITableViewCell 的高度

swift - 如何使用 swift 3 和 iOS 10 将 zip 文件上传到 FTP 服务器?

swift - Swift 中的多个动画过渡

ios - 获取当前页码垂直 UIScrollView ios