如何根据标记值显示/隐藏UITableView指定分区及自定义单元格
优化UITableView分区显示与Cell配置的方案
你的实现能满足需求,但存在冗余判断和重复代码,这里提供几个优化方向及重构后的代码:
1. 统一注册所有Cell,避免条件注册隐患
原代码仅在flagValue为true时注册UPPercentageCell,若后续flagValue动态切换(比如从false改为true),会因未注册Cell导致崩溃。直接注册所有所需Cell即可,注册操作开销极低,不会影响性能。
2. 简化分区与行数的逻辑判断
把重复的flagValue判断简化,用更直观的逻辑对应分区职责:
- 分区数量直接用三元表达式简化判断
- 行数判断时先明确当前分区类型,减少嵌套层级
3. 提取重复的Cell配置逻辑
原代码中RadioButtonTableViewCell的配置代码完全重复,提取为单独方法,既减少冗余,也方便后续维护。
4. 修复Header高度的逻辑问题
原代码只要flagValue为true就返回固定高度,会导致两个分区Header高度一致,调整为根据分区索引返回对应高度,逻辑更准确。
5. 避免硬写标识符,使用类静态常量
替换原代码中硬写的字符串标识符,改用Cell类的静态identifier常量,避免拼写错误。
重构后的代码
override func viewDidLoad() { super.viewDidLoad() registerCells() } func registerCells() { // 统一注册所有需要的Cell,不受flagValue状态影响 DetailsTableview.register(RadioButtonTableViewCell.nib, forCellReuseIdentifier: RadioButtonTableViewCell.identifier) DetailsTableview.register(UPPercentageCell.nib, forCellReuseIdentifier: UPPercentageCell.identifier) } func numberOfSections(in tableView: UITableView) -> Int { // 简化分区数量判断 return flagValue ? 2 : 1 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // 根据分区索引返回对应高度 if flagValue && section == 0 { return 20 } return 40 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let isPercentageSection = flagValue && section == 0 return isPercentageSection ? 1 : (response?.data?.count ?? 0) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let isPercentageSection = flagValue && indexPath.section == 0 if isPercentageSection { let cell = tableView.dequeueReusableCell(withIdentifier: UPPercentageCell.identifier, for: indexPath) as! UPPercentageCell cell.percentage = "20" // 动态值可按需调整 cell.isUserInteractionEnabled = false return cell } else { return configureRadioButtonCell(at: indexPath, tableView: tableView) } } // 提取RadioButtonCell的配置逻辑,消除重复代码 private func configureRadioButtonCell(at indexPath: IndexPath, tableView: UITableView) -> RadioButtonTableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RadioButtonTableViewCell.identifier, for: indexPath) as! RadioButtonTableViewCell let title = response?.data?[indexPath.row] ?? "" cell.displayDataToUI(title: title, currentIndexpath: indexPath, selectedIndexpath: selectedIndexpath ?? IndexPath()) cell.radioButtonClicked = { [weak self] indexpath in self?.saveButton.isUserInteractionEnabled = true self?.reloadTableviewFromSelectedIndexpath(indexpath: indexpath) } return cell }
额外优化建议
- 若
flagValue可能动态变化,修改值后记得调用tableView.reloadData()刷新界面 - 可考虑将分区配置(是否显示、行数、Cell类型等)封装为
TableSection模型数组,进一步解耦逻辑,方便后续扩展更多分区场景
内容的提问来源于stack exchange,提问作者Anilkumar iOS Developer
相关产品推荐
相关产品推荐

