我现在正在测试 UICollectionViewCell 中有一个变量...这是我的 cellforitem
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: chatCellId, for: indexPath) as! ChatCell
c.userDidSend = (indexPath.item % 2 == 0) ? true : false
return c
}
在 ChatCell 类中,我使用 var userDidSend: Bool? 初始化变量 ,但是每当我测试变量时,它总是返回 nil。下面是针对每个单元格测试变量的位置。
override func setupViews() {
super.setupViews()
if userDidSend == true {
setupSentChat()
} else if userDidSend == false {
setupRecievedChat()
}
print(userDidSend)
}
除了这个特殊问题之外,一切正常。 想法?
编辑: setupViews 在单元格 View 初始化时被调用。
override init(frame: CGRect){
super.init(frame: frame)
setupViews()
}
最佳答案
使用自定义 setter 似乎已经解决了这个问题。
var userDidSend: Bool? {
didSet {
if userDidSend == true {
setupSentChat()
} else if userDidSend == false {
setupRecievedChat()
}
}
}
关于swift - CellForItematIndexPath 无法设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855368/