Swift+Storyboard实现带分组与复选框的TableView及选中ID收集
实现带分组的TableView及选中ID收集方案
一、配置TableView分组数据源
首先在ViewController中定义分组数据数组,作为TableView的核心数据源:
var sections: [InteresseSection] = []
在viewDidLoad中完成TableView初始化与数据加载:
override func viewDidLoad() { super.viewDidLoad() // 注册自定义Cell tableView.register(InteresseCell2.self, forCellReuseIdentifier: "InteresseCell2") tableView.dataSource = self tableView.delegate = self // 加载结构化数据 sections = getData() }
实现TableView分组相关的数据源方法:
extension YourViewController: UITableViewDataSource { // 返回分组总数 func numberOfSections(in tableView: UITableView) -> Int { return sections.count } // 返回每组的选项数量 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].interesses.count } // 设置分组头部标题 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section].title // 假设InteresseSection包含title属性 } // 复用并配置自定义Cell func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "InteresseCell2", for: indexPath) as! InteresseCell2 let interesse = sections[indexPath.section].interesses[indexPath.row] // 绑定数据到Cell cell.configure(with: interesse) // 绑定复选框点击回调 cell.onCheckBoxToggle = { [weak self] isSelected in self?.sections[indexPath.section].interesses[indexPath.row].isSelected = isSelected self?.syncSelectedIds(interesse.id, isSelected: isSelected) } return cell } }
二、自定义Cell(InteresseCell2)配置
给Cell添加数据绑定方法与选中状态回调,确保复选框的交互能通知外部:
class InteresseCell2: UITableViewCell { @IBOutlet weak var checkBoxBtn: CheckBoxButton! @IBOutlet weak var interestTitleLabel: UILabel! // 回调闭包,传递复选框选中状态变化 var onCheckBoxToggle: ((Bool) -> Void)? override func awakeFromNib() { super.awakeFromNib() // 绑定复选框点击事件 checkBoxBtn.addTarget(self, action: #selector(onCheckBoxClicked), for: .touchUpInside) } // 配置Cell显示内容 func configure(with interesse: Interesse) { interestTitleLabel.text = interesse.title // 假设Interesse包含title属性 checkBoxBtn.isSelected = interesse.isSelected } @objc private func onCheckBoxClicked() { checkBoxBtn.isSelected = !checkBoxBtn.isSelected onCheckBoxToggle?(checkBoxBtn.isSelected) } }
同时给Interesse模型添加isSelected属性,用于持久化选中状态:
struct Interesse { let id: Int let title: String var isSelected: Bool // 新增属性记录选中状态 // 其他已有属性 }
三、选中ID的收集与管理
在ViewController中维护一个集合存储选中的ID,提供同步方法:
var selectedInterestIds: Set<Int> = [] private func syncSelectedIds(_ id: Int, isSelected: Bool) { if isSelected { selectedInterestIds.insert(id) } else { selectedInterestIds.remove(id) } // 后续提交或使用时,直接读取selectedInterestIds即可 }
四、额外注意事项
- 在
getData()方法解析JSON时,初始化Interesse需将isSelected默认设为false - 若需支持分组全选/反选,可在分组头部添加按钮,点击时遍历该组所有
Interesse更新状态并同步ID集合 - 开启TableView自动布局(设置
estimatedRowHeight和rowHeight = UITableView.automaticDimension),避免Cell显示异常
内容的提问来源于stack exchange,提问作者Cristian Capannini
相关产品推荐
相关产品推荐

