引用不可见的单元格

时间:2017-04-10 17:58:52

标签: ios swift uitableview

我试图在委托方法中引用一个单元格,didSelectRowAt使用此代码:

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

该单元格在被引用时不在视图中(不可见),因此不再出列。因为它不在视图中,所以上面的if let语句失败了。如何引用不在视图中的单元格?

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

2 个答案:

答案 0 :(得分:0)

您需要在更新数据模型后致电reloadRows(at:with:)。然后,UITableView会要求您的UITableViewDataSource向相应的单元格提供新数据。

self.tableView.reloadRows(at: [expandedIndexPath!], with: .automatic)

答案 1 :(得分: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实现只能重新加载第二行,但这将是一个优化。

相关问题