[英]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)")
}
當你在寫作
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.