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

如何实现单选功能:避免UITableView多个列表项同时被勾选

实现TableView Cell单选(点击按钮勾选,切换单元格时清除之前勾选)

你当前的写法是每个cell独立维护勾选状态,cell之间没有联动机制,所以点击其他cell时,之前的cell不会自动清除勾选。要实现单选功能,得把选中状态的控制权放到TableView所在的ViewController里,让它统一管理选中的cell。

第一步:修改ViewController,统一管理选中状态

在你的TableView所在的ViewController中添加变量记录选中行,同时在数据源方法里控制cell的勾选状态:

class YourViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    // 记录当前选中的行,nil表示无选中状态
    var selectedRow: Int?
    
    // 示例数据源,替换成你实际的语言列表
    let languages = ["中文", "英文", "日文", "韩文"]
    
    // MARK: - UITableView DataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return languages.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewTableViewCell", for: indexPath) as! NewTableViewCell
        cell.languageText.text = languages[indexPath.row]
        
        // 根据当前行是否选中,设置勾选标记
        cell.checkLabel?.text = selectedRow == indexPath.row ? "\u{02713}" : ""
        
        // 绑定按钮点击回调,让ViewController处理选中逻辑
        cell.onButtonTap = { [weak self] in
            // 点击已选中的cell则取消选中,否则切换选中行
            self?.selectedRow = self?.selectedRow == indexPath.row ? nil : indexPath.row
            tableView.reloadData()
        }
        
        return cell
    }
}

第二步:修改NewTableViewCell,移除本地状态变量,添加回调闭包

删掉cell里的count和doesContainTick,用回调闭包把按钮点击事件传递给ViewController:

class NewTableViewCell: UITableViewCell {
    @IBOutlet var langaugeBox: UIView!
    @IBOutlet var languageText: UILabel!
    @IBOutlet var checkLabel: UILabel?
    
    // 按钮点击回调闭包,用于通知ViewController更新选中状态
    var onButtonTap: (() -> Void)?
    
    @IBAction func selectButton(_ sender: UIButton) {
        guard sender.isEnabled else { return }
        // 触发回调,把点击事件交给ViewController处理
        onButtonTap?()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

补充说明

  • 这种方式把选中状态统一交给ViewController管理,所有cell的勾选状态都由cellForRowAt方法设置,确保切换选中时所有cell的状态同步更新。
  • 如果不需要“点击已选中cell取消勾选”的功能,把回调里的代码改成self?.selectedRow = indexPath.row即可。
  • 确保你的TableViewCell复用标识符和代码里的"NewTableViewCell"一致,避免复用出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:42:15