Swift中 dismiss tableView 后如何保留选中行的对勾标记
实现单选筛选TableView的选中状态持久化
核心逻辑
要实现再次打开筛选页时保留之前的选中状态,关键是在首页VC和筛选VC之间共享选中记录,让筛选VC每次加载时能读取历史选中信息并刷新UI。
具体实现步骤
1. 首页VC存储选中状态
在首页VC中声明变量,用来保存筛选项的唯一标识(推荐用模型ID,比索引值更可靠):
// 首页VC var selectedFilterId: String? // 假设你的筛选模型有唯一id字段
2. 打开筛选VC时传递选中状态
点击首页筛选按钮,跳转/弹出筛选VC时,把当前的选中ID传过去:
// 首页VC中打开筛选VC的代码 @IBAction func filterButtonTapped(_ sender: UIButton) { let filterVC = FilterTableViewController() filterVC.selectedId = self.selectedFilterId // 用present弹出(如果是push跳转,逻辑类似) present(filterVC, animated: true) }
3. 筛选VC接收并渲染选中状态
在筛选VC中接收首页传来的选中ID,在数据源方法里判断并显示对勾:
// 筛选VC class FilterTableViewController: UITableViewController { // 接收首页传递的已选中ID var selectedId: String? // 筛选数据源(自定义模型数组,需包含id、name等字段) var filterData: [FilterModel] = [] override func viewDidLoad() { super.viewDidLoad() tableView.allowsSelection = true tableView.allowsMultipleSelection = false } // 渲染单元格时判断是否显示对勾 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FilterCell", for: indexPath) let model = filterData[indexPath.row] cell.textLabel?.text = model.name // 匹配已选中ID,设置对勾 cell.accessoryType = model.id == selectedId ? .checkmark : .none return cell } // 选中行时更新状态并回调给首页 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedModel = filterData[indexPath.row] // 取消之前选中行的对勾 if let prevSelectedIndex = filterData.firstIndex(where: { $0.id == selectedId }) { if let prevCell = tableView.cellForRow(at: IndexPath(row: prevSelectedIndex, section: 0)) { prevCell.accessoryType = .none } } // 设置当前行对勾并更新选中ID selectedId = selectedModel.id if let currentCell = tableView.cellForRow(at: indexPath) { currentCell.accessoryType = .checkmark } // 通过闭包把选中ID传回首页 onSelectFilter?(selectedModel.id) } // 定义闭包用于回调首页 var onSelectFilter: ((String) -> Void)? }
4. 筛选VC关闭时同步状态到首页
在首页打开筛选VC时,设置闭包接收选中ID并保存:
// 首页VC中打开筛选VC的代码补充 @IBAction func filterButtonTapped(_ sender: UIButton) { let filterVC = FilterTableViewController() filterVC.selectedId = self.selectedFilterId // 闭包回调更新首页的选中状态 filterVC.onSelectFilter = { [weak self] selectedId in self?.selectedFilterId = selectedId // 可选:刷新首页TableView应用筛选条件 self?.tableView.reloadData() } present(filterVC, animated: true) }
5. 可选:本地持久化选中状态
如果需要APP重启后仍保留选中状态,用UserDefaults存储:
// 首页VC中保存选中状态 UserDefaults.standard.set(selectedFilterId, forKey: "SelectedFilterId") // 首页VC加载时读取 override func viewDidLoad() { super.viewDidLoad() selectedFilterId = UserDefaults.standard.string(forKey: "SelectedFilterId") }
内容的提问来源于stack exchange,提问作者DMD
相关产品推荐
相关产品推荐

