iOS UICollectionView初始化并更新自定义单元格

时间:2017-01-28 17:51:41

标签: ios uicollectionview uicollectionviewcell

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

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])
}

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

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时,首先是init单元格(使用setEmpty()方法);然后在点击之后,更新单元格,然后调用第一个函数,但是通过此

获取单元格
collectionView.dequeueResuableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

显示内部的值仍为零,因此单元格不是最新的。我该怎么解决这个问题?或者我的实现是合乎逻辑的(我应该在其他地方初始化单元格而不是使用此

check if it's nil -> then init

逻辑)?

1 个答案:

答案 0 :(得分:0)

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中的任何状态区分机制重新加载单元格,考虑cellForItemAt将引用该状态并应用该外观更改。