You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在didSelectRow中修改UITableView分区标题的文本颜色

解决方案

要修改点击分区对应自定义header的标题颜色,你需要获取当前分区已显示的header视图(不要用dequeueReusableHeaderFooterView,它会返回复用池中的视图,而非当前屏幕上的目标header),具体实现逻辑如下:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch viewModel?.sections[indexPath.section].cellType {
    case .selectionCell:
        let cell = tableView.cellForRow(at: indexPath) as? CheckboxesTableViewCell
        guard let checkboxOption = viewModel?.sections[indexPath.section].checkboxOptions?[indexPath.row] else { return }
        checkboxOption.isSelected = !checkboxOption.isSelected
        cell?.update(viewModel: checkboxOption)
        
        // 新增修改header标题颜色的逻辑
        guard let headerView = tableView.headerView(forSection: indexPath.section) as? QuestionaryTableViewHeader else {
            return
        }
        // 根据需求设置颜色,示例:判断当前分区是否有选中项,切换标题颜色
        let hasSelectedItem = viewModel?.sections[indexPath.section].checkboxOptions?.contains(where: { $0.isSelected }) ?? false
        headerView.titleLabel.textColor = hasSelectedItem ? .systemRed : .label
        
    case .textCell:
        debugPrint("Text field tapp")
    case .none:
        break
    }
}

注意事项

  • 确保你的QuestionaryTableViewHeader类中,titleLabel是可外部访问的属性(如果是私有属性,需添加公开方法或计算属性来修改颜色)
  • 颜色切换逻辑可根据实际需求调整,比如直接设置固定颜色、根据单个选项选中状态变化等

内容的提问来源于stack exchange,提问作者Milos Mandic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:45:41