簡體   English   中英

單元格變量為零,其中設置了值 collectionview 索引路徑

[英]cell variable is nil where value was set collectionview index path

我花了很多時間..但我不知道為什么它不起作用..調用索引路徑的單元格並正確設置值但單元格類我發現值為零..如果您需要任何信息,請告訴我。

在我的 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
    }

對於細胞:

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

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

         print("shopCategory :-> ...i am calling from cell :\(shopCategory)")
}

因為你的awakeFromNib先叫方法,然后cellForRow 。你要分配變量的值cellForRow所以當第一個項目執行它的價值是nil

解決方案

  1. 您的自定義單元類中的變量

    var myVar : String?
  2. 在您的自定義單元類中創建一個方法

    func myMethod(str : String){ myVar = str print("var : \\(myVar)") }
  3. cellForItem ,像這樣調用你的函數

    cell.myMethod(str: "343")

輸出

在此處輸入圖片說明

當你在寫作

let cell = collectionView.dequeueReusableCell(withReuseId`entifier: "MenuBarItemDetail", for: indexPath) as! MenuBarItemDetail`

那時“覆蓋 init(frame: CGRect)”被調用。 並且在初始化時沒有為 shopCategory 分配任何值,這就是您獲得 nil 的原因。

在 MenuBarItemDetail 中添加一個函數“getShopCategory”,當你想要訪問 shopCategory 的值時,你可以使用 getShopCategory 函數來獲取它。

import Foundation
import UIKit

    class MenuBarItemDetail: UICollectionViewCell  {
        var shopCategory : String?

        func  getShopCategory()  {
         print("shopCategory :-> ...i am calling from cell :\(shopCategory)")
        }


    }

控制器類

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

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuBarItemDetail", for: indexPath) as! MenuBarItemDetail
        cell.shopCategory = "600"
        print(cell.shopCategory)
        cell.getShopCategory()
        return cell
    }

cell 是 MenuBarItemDetail 的當前實例,因此它將返回 shopCategory 的指定值

請讓我知道它是否適合您。 謝謝

暫無
暫無

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

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