Swift中如何为UITableView Cell添加带勾选标记的单选按钮
实现UITableView单选勾选按钮的方案
1. 维护全局选中状态变量
在MatchFriendsViewController中添加一个属性,用来记录当前选中的行,确保单选逻辑的一致性:
var selectedIndexPath: IndexPath?
2. 给ContactTableViewCell添加勾选控件与状态更新方法
不管是用自定义UIButton还是第三方CheckBox控件,都要在cell中封装状态更新逻辑,避免控制器代码冗余:
// 假设用UIButton实现勾选(也可替换为你用的CheckBox控件) class ContactTableViewCell: UITableViewCell { @IBOutlet weak var checkButton: UIButton! // 自定义方法设置选中状态 func updateCheckState(isSelected: Bool) { // 用自定义图片区分选中/未选中 let checkImage = isSelected ? UIImage(named: "checked_icon") : UIImage(named: "unchecked_icon") checkButton.setImage(checkImage, for: .normal) // 如果用第三方CheckBox控件,直接设置其选中状态即可 // checkBox.isSelected = isSelected } }
3. 在cellForRowAt中绑定选中状态
在控制器的tableView(_:cellForRowAt:)方法中,根据selectedIndexPath给cell设置勾选状态,解决cell复用导致的状态错乱问题:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell", for: indexPath) as! ContactTableViewCell // 先设置联系人名称、头像等基础信息 let contact = contacts[indexPath.row] cell.nameLabel.text = contact.name // 绑定勾选状态 let isCurrentSelected = indexPath == selectedIndexPath cell.updateCheckState(isSelected: isCurrentSelected) return cell }
4. 处理cell点击事件,实现单选逻辑
在tableView(_:didSelectRowAt:)中更新选中状态,只刷新状态变化的行,提升性能:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 刷新之前选中的行(取消勾选) if let oldIndex = selectedIndexPath { tableView.reloadRows(at: [oldIndex], with: .automatic) } // 更新当前选中行 selectedIndexPath = indexPath tableView.reloadRows(at: [indexPath], with: .automatic) // 可选:取消cell的默认高亮状态 tableView.deselectRow(at: indexPath, animated: true) }
5. 完善第三方CheckBox控件的交互(若使用)
如果用的是第三方CheckBox,建议关闭其自身的交互,统一通过cell点击来控制状态,避免单独点击控件导致逻辑混乱:
// 在cell的awakeFromNib方法中设置 override func awakeFromNib() { super.awakeFromNib() checkBox.userInteractionEnabled = false }
内容的提问来源于stack exchange,提问作者airsoftFreak
相关产品推荐
相关产品推荐

