重新加载UITableView后如何维护突出显示的多个UITableView行?



我有一个UITableView。
我可以选择多个单元格使它们突出显示。
但是,每当我重新加载应用程序时,所选和突出显示的状态都会消失。
我想我需要在"viewDidAppear"和"didSelectRowAt"中放置一些代码。但我对具体代码一无所知。
我必须在此语法中放入什么?

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}
}

我建议你添加到数据源项目字段选中,并在方法cellForRowAtIndexPath中由你的数据源项目配置。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cellClass = (self.cellClass(for: indexPath) ?? self.cellClasses.first) else { return UITableViewCell() }
let cell = tableView.dequeueReusableCell(withIdentifier: cellClass.identifier, for: indexPath)
if let configurable = cell as? ConfigurableComponent, let object = self.object(at: indexPath) {
let item = self.dataSource[indexPath.row]
configurable.selected =  item.selected
}
return cell
}

当调用didSelectRowAt时,只需获取项目并更改所选字段,示例:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.dataSource[indexPath.row]
item.selected = !item.selected
tableView.reloadData()
}

最新更新