Reputation: 425
i spend lot of time .. but i can't figure out why it is not working .. cell for index path called and set value properly but cell class i found nil value .. if your need any information then let me know .
in my collectionview index path
in collectionview cell
here is my code :
for 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
}
for 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)")
}
Upvotes: 3
Views: 931
Reputation: 9503
Because your awakeFromNib
method called first and then cellForRow
.You are assigning the value of variable in cellForRow
so when first project executes its value is nil
.
Solution
your variable in your custom cellclass
var myVar : String?
Create a method in your custom cellclass
func myMethod(str : String){
myVar = str
print("var : \(myVar)")
}
in cellForItem
, call your function like this
cell.myMethod(str: "343")
Output
Upvotes: 5
Reputation: 475
When you are writing
let cell = collectionView.dequeueReusableCell(withReuseId`entifier: "MenuBarItemDetail", for: indexPath) as! MenuBarItemDetail`
At that time "override init(frame: CGRect)" is called. and no value is assigned to shopCategory at the time of init that's the reason you are getting nil.
Add a function "getShopCategory" into MenuBarItemDetail and when every you want to access the value of shopCategory you can get that using getShopCategory function.
import Foundation
import UIKit
class MenuBarItemDetail: UICollectionViewCell {
var shopCategory : String?
func getShopCategory() {
print("shopCategory :-> ...i am calling from cell :\(shopCategory)")
}
}
Controller Class
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 is the current instance of MenuBarItemDetail so it will return assigned value of shopCategory
Please let me know if it's working for you. Thank you
Upvotes: 3