2017-04-10 42 views
1

我试图在委托方法来引用一个细胞,使用此代码didSelectRowAt:参考一个细胞,其是不可见的

if let cell = self.tableView.cellForRow(at: expandedIndexPath!) as? FeedInsertTableCollectionViewCell{} 

即小区不在它是时间的视图(不可见)被引用,因此不再被取消。因为它不在视图中,所以上面的if语句失败。如何引用不在视图中的单元格?

为了让您更好地了解我期待的功能。当用户单击一个单元格时,我需要清除之前单元格中的数据并将数据加载到用户单击的单元格中。因为上面的let语句失败,所以我无法清除之前单元格中的数据,因为我无法引用或访问它。

+3

您不需要访问任一单元格。更新您的表的数据源使用的数据模型,然后通知表视图重新加载受影响的索引路径。 – rmaddy

+0

*不在视图中的单元不存在。 – vadian

回答

0

我创建了一个小项目来展示它可以完成的一种方式。 Git it enter link description here

它是如何工作的?

的属性声明,其中最新的点击细胞将被存储:

var lastSelectedCells = [IndexPath]() 

因为我们希望有在该阵列的顶部的最新单击的单元格,这里就是我们做的方法“DidSelectCellAtRowIndexPath” :

lastSelectedCells.insert(indexPath, at: 0) 

我们也想更新已被点击(含现任在内)之前的细胞,因此,右后上方,我们执行:

tableView.reloadRows(at: lastSelectedCells, with: .automatic) 

逻辑的其余部分是在“的cellForRowAtIndexPath”方法,如下所示(与项目一点简化):

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "NiceCell") as! MyBeautifulCell 
     if let index = lastSelectedCells.index(of: indexPath) { 
      cell.centeredLabel?.text = "Cell tapped \(index) times ago!" 
     } else { 
      cell.centeredLabel?.text = "Uhmpf, this cell was never tapped!" 
     } 
     return cell 
    } 

即:如果当前indexPath是阵列中,我们设置将单元格的文本作为它的索引,否则我们设置一些脾气暴躁的文本。

我不知道你的整个项目,但这应该足以让你实现你想做的事情。

既然你说:我需要在前面的细胞清除数据...... 你可以如下改变方法:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     guard let cell = tableView.dequeueReusableCell(withIdentifier: "NiceCell") as? MyBeautifulCell else { 
      fatalError("Table Configuration Error!") 
     } 

     if let index = lastSelectedCells.index(of: indexPath) { 
      switch index { 
      case 0: 
       cell.centeredLabel?.text = "Cell tapped" 
      default: 
       cell.centeredLabel?.text = "CLEARED" 
      } 
     } else { 
      cell.centeredLabel?.text = "Uhmpf, this cell was never tapped!" 
     } 
     return cell 
    } 

如果你走这条路,在reloadRows实现可以重新加载只有第二最后一行,但这将是一个优化。

相关问题