单元格变量为零,其中设置了值 collectionview 索引路径

cri*_*ika 2 ios swift swift2

我花了很多时间..但我不知道为什么它不起作用..调用索引路径的单元格并正确设置值但单元格类我发现值为零..如果您需要任何信息,请告诉我。

在我的 collectionview 索引路径中

在此处输入图片说明

在 collectionview 单元格中

在此处输入图片说明

这是我的代码:

对于集合视图:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: menuBarItemDetailId, for: indexPath) as! MenuBarItemDetail
        cell.shopCategory = "600"
        print(cell.shopCategory)
        return cell
    }
Run Code Online (Sandbox Code Playgroud)

对于细胞:

class MenuBarItemDetail: UICollectionViewCell , UITableViewDataSource , UITableViewDelegate {
    var shopCategory : String?

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

         print("shopCategory :-> ...i am calling from cell :\(shopCategory)")
}
Run Code Online (Sandbox Code Playgroud)

dah*_*boy 5

因为您的awakeFromNib方法首先调用然后cellForRow.You 分配变量的值,cellForRow所以当第一个项目执行时,它的值为nil.

解决方案

  1. 您的自定义单元类中的变量

    var myVar : String?
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在您的自定义单元类中创建一个方法

    func myMethod(str : String){
        myVar = str
        print("var : \(myVar)")        
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. cellForItem,像这样调用你的函数

    cell.myMethod(str: "343")
    
    Run Code Online (Sandbox Code Playgroud)

输出

在此处输入图片说明