我正在尝试使用以下代码在委托(delegate)方法 didSelectRowAt 中引用一个单元格:
if let cell = self.tableView.cellForRow(at: expandedIndexPath!) as? FeedInsertTableCollectionViewCell{}
该单元格在被引用时不在 View 中(不可见),因此不再出队。因为它不在 View 中,所以上面的 if let 语句失败了。如何引用不在 View 中的单元格?
让您更好地了解我想要做什么。当用户单击一个单元格时,我需要清除前一个单元格中的数据并将数据加载到用户单击的单元格中。因为上面的 if let 语句失败,我无法清除前一个单元格中的数据,因为我无法引用或访问它。
最佳答案
我已经创建了一个小项目来展示一种实现方法。混帐它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 实现只能重新加载倒数第二行,但这将是一种优化。
关于ios - 引用不可见的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329891/