获取indexPath的didSelectItemAt上的值并将其添加到委托/协议中以填充标头单元格

时间:2019-05-22 18:52:58

标签: ios swift uicollectionview delegates protocols

使用协议/委托并从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)

那个宾果游戏正在打印我需要的值。很好,就在那里。

现在,我不能在该函数内部使用协议的方法,因为执行不正确,因此编译器或Xcode会说,嘿,您将方法声明为常规方法,而不是嵌套方法。

//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
    }
}

想要在这方面引导我的任何人,帽子都关闭了。

2 个答案:

答案 0 :(得分:1)

不使用委托,但可以使用

解决者:

1)转到collectionView的控制器。制作一个新变量来存储项目。

// 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? 

最后,在该类中,您应该具有方法 viewForSupplementaryElementOfKind ,在其中注册HeaderCell,然后仅添加...

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

header.lbl.text = newVar.whatEverYourDataIs

通用性很小,但可以。 :)

答案 1 :(得分:0)

我认为您可以将其添加到didSelectItemAt indexPath中当前代码的末尾:

guard let header = collectionView.supplementaryView(forElementKind: "yourElementKind", at: indexPath) as? HeaderCell else { return }

header.lbl.text = bingo

collectionView.reloadData()

编辑:现在保留所有其他内容,以确保您首先获得良好的结果。

让我知道这是否可行,很高兴回来查看。