swift - CellForItematIndexPath 无法设置变量

标签 swift uicollectionview uicollectionviewcell

我现在正在测试 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/

相关文章:

ios - 为什么我只能在 TableView Swift 中展示我的第一部分?

swift - 如何在不破坏 "Menu"按钮默认行为的情况下在 tvOS 游戏中设置主菜单

ios - UICollectionView 中未声明的标识符错误

ios - 点击该单元格时,如何访问 uicollectionviewcell 内标签的文本属性? ( swift )

swift - 如何在 Swift 中使用多个标签单独调整 UICollectionViewCells 的大小?

swift - 从 Swift 中的 UICollectionView 继续

ios - 移动行(在 :to:) doesn't work if the UITableView has many items

ios - SwiftUI 中水平居中 View

xcode - 如何快速从 UICollectionView 中的 UIView 中删除焦点阴影?

ios - 如何减少图像宽度和高度取决于使用约束的手机?