Table View Cell 无论如何都保持突出显示

Table View Cell Stays Highlighted No Matter What

我的基于故事板的 UITableViewController 子类在用户点击其中一个 table 视图单元格时将另一个视图控制器推送到导航中。

我正在使用 segue 来完成此操作,并且 not 以编程方式使用pushViewController(:animated:).

我遇到的问题 是我的 table 视图单元一直保持突出显示(浅灰色),即使在弹出视图控制器之后(同样,使用'unwind' 转场)。清除它的唯一方法是调用 tableView.reloadData().


我试过:

  1. 设置:

    self.clearsSelectionOnViewWillAppear = true
    

    in viewDidLoad()(应该不是必需的,因为它已经是默认值:模板代码已 self.clearsSelectionOnViewWillAppear = false 注释掉,建议取消注释以覆盖默认功能)。

  2. 还有:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        if let indexPath = tableView.indexPathForSelectedRow {
            tableView.deselectRow(at: indexPath, animated: true)
        }
    }
    

    ...无济于事。

    编辑: 原来 viewDidAppear() 而不是 在导航弹出时被调用,只有在被添加到视图层次结构之后(例如,addSubview())。将此代码放在 viewWillAppear() 就可以了。但是我在这个 post 结尾的问题仍然存在。

  3. 我也试过实现这个方法:

    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    

    ...但它没有被调用(可能是因为 segue?)

唯一成功取消突出显示单元格的是调用:

tableView.deselectRow(at: indexPath, animated: true)

...来自 prepareForSegue()。但这发生在 push 上,我想在 pop.

上取消突出显示我的单元格

我是否需要为推送(单元格点击)segue 设置专用的展开方法,并在那里取消突出显示?

为什么它不能开箱即用,即使我正在子类化 UITableViewController

第三个选项应该可以,我想你只是不小心自动完成了 didDeselectRow,而不是 didSelectRow。

就像你提到的那样,使用 tableView.deselectRow(at: indexPath, animated: true)

但是,而不是将其放入:

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

你应该把它放在:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // You other cell selected functions here ...
    // then add the below at the end of it.
    tableView.deselectRow(at: indexPath, animated: true)
}

didDeselectRowAt 将不会被调用,直到一行被 deselected。因此,为了删除 select 单元格,您应该将其添加到 didSelectRow 中。这样,每当一个单元格被 selected 并且 didSelectRow 被触发时,您将 运行 您的其他代码以及 de-select 它末尾的单元格。