簡體   English   中英

iOS CollectionView標頭不顯示

[英]iOS CollectionView Header doesn't show

我試圖將分段控件添加到我的標頭中,但是我在這樣做時遇到了麻煩。 在此示例中,為了簡化起見,我添加了一個Label,但也未顯示。 有人可以告訴我為什么這種情況不會發生嗎?

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



}

我在一個新項目中嘗試了您的代碼,但您缺少兩個關鍵步驟:注冊補充視圖和設置標頭的大小。

prepareCollectionView函數中,還需要注冊標題視圖:

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

您還需要實現另一個委托函數,以提供標頭視圖的大小:

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

這證明它有效。 (我無法使用您的自定義顏色,這就是為什么所有顏色都是橙色和灰色的原因。)

集合視圖標題屏幕截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM