简体   繁体   中英

iOS CollectionView Header doesn't show

Im trying to add a segmented control onto my header but I am having trouble doing this. In this example to make things simpler I am adding a Label but that is also not showing. Can someone tell me why this is not happening?

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")
    }



}

I tried your code in a new project, and you are missing two key steps: registering the supplementary view and setting the size of your header.

In your prepareCollectionView function, you also need to register the header view:

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

You also need to implement another delegate function giving the size of your header view:

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

Here is proof that it works. (I didn't have access to your custom colors, which is why everything is orange and gray.)

集合视图标题屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM