Search code examples
iosswiftuicollectionviewdelegatesprotocols

Taking the value on didSelectItemAt for indexPath and add it to a delegate / protocol to populate a header cell


Using protocol / delegate & retrieve the data from didSelectItemAt (collectionViews).

// This class have the data 
// WhereDataIs: UICollectionViewController
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        //Pass some data from the didSelect to a delegate

        let test = things[indexPath.item]
        guard let bingo = test.aThing else { return }
        print("bingo: ", bingo)

That bingo is printing the value that I need. So pretty good right there.

Now, I can't use the method of the protocol inside of that function, that's bad execution so the compiler or Xcode says hey, you will declare the method as a regular method, not the nested way.

//Bridge
protocol xDelegate {
    func x(for headerCell: HeaderCell)
}
//This is the class that need the data
//class HeaderCell: UICollectionViewCell
var xDelegate: xDelegate?

//it's init()

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

        let sally = WhereDataIs()
        self.xDelegate = sally

        xDelegate?.x(for: self)
}
// This extension is added at the end of the class WhereDataIs()
// Inside of this class is it's delegate.

var xDelegate: xDelegate? = nil

extension WhereDataIs: xDelegate {
    func x(for headerCell: HeaderCell) {
        //Smith value will work because it's dummy
        headerCell.lbl.text = "Smith"

       // What I really need is instead of "Smith" is the value of didselectItemAt called bingo.
headerCell.lbl.text = bingo
    }
}

Hat's off for anyone who would like to guide me in this.


Solution

  • Not using delegates, but it will work

    Solved by:

    1) go to the controller of the collectionView. make a new variable to store the items.

    // Pass the item object into the xController so that it can be accessed later. 
    //(didSelectItemAt)
     xController.newVar = item 
    
    //xController class: UICollectionView... 
    // MARK: - Properties 
    var newVar: Thing? 
    

    Finally in that class, you should have the the method viewForSupplementaryElementOfKind in which you register the HeaderCell and then just add...

    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as! HeaderCell
    
    header.lbl.text = newVar.whatEverYourDataIs
    
    

    Little generic but it works. :)