【问题标题】:iOS UICollectionView init and update custom celliOS UICollectionView 初始化和更新自定义单元格
【发布时间】:2017-06-14 06:04:29
【问题描述】:

我正在尝试实现一个支持用户点击的自定义单元格。之前相关的功能有:

func collectionView(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueResuableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
    cell.setEmpty() // to init the cell
    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath) as ! CustomCell
    //implementations
    self.collectionView.reloadItem(at: [indexPath])
}

然后我注意到点击后,第二个函数首先被调用,但第一个函数也被调用,这意味着点击后我的单元格仍然会设置为空,所以我将第一个函数更改为:

let cell = collectionView.dequeueResuableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
if cell.valueInside == nil {
    cell.setEmpty() // this will set valueInside to be a non-nil value
}
return cell

但它仍然无法正常工作。我跟踪了这​​个过程:第一次加载 UI 时,首先初始化单元格(使用 setEmpty() 方法);然后点击后更新cell,然后调用第一个函数,但是这个得到的cell

collectionView.dequeueResuableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

表明里面的值仍然是 nil,所以单元格并不是最新的。我应该如何解决这个问题?或者我的实现是否合乎逻辑(我应该在其他地方初始化单元而不是使用这个

check if it's nil -> then init

逻辑)?

【问题讨论】:

    标签: ios uicollectionview uicollectionviewcell


    【解决方案1】:
    func collectionView(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    

    每次查询类似单元格时都会调用

    collectionView.cellForItem(at: indexPath)
    

    self.collectionView.reloadItem(at: [indexPath])
    

    最好的使用方法是声明一个像数组一样的类级别变量来保存支持的数据,然后为单元格创建从该数组获取数据并在您的didSelectItemAt 更新该数组,然后强制集合视图仅更新该单元格。

    // In your class scope
    private var arData: [String] = ["One", "Two", "Three"]           // This could be populated in viewDidLoad as well
    // .... rest of your code
    func collectionView(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueResuableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
       //...
       if indexPath.row < arData.count {
          cell.valueInside = arData[indexPath.row]
       } else {
          cell.valueInside = "Default Value"
       }
       return cell
    }
    // ....
    func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //implementations
        if indexPath.row < arData.count {
          arData[indexPath.row] = "newValue"
          self.collectionView.reloadItem(at: [indexPath])
        }
    }
    

    这是关于现在如何正确更改单元格视图内容的逻辑,如果您想再次更改其外观,您应该设置标志或您在didSelectItemAt 中拥有的任何状态区分机制,然后考虑@987654327 重新加载单元格@ 将引用该状态并应用该外观更改。

    【讨论】: