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

如何通过代码为指定UITableView单元格添加UISwitch

解决UITableView仅特定单元格显示UISwitch的问题

你的问题出在tableView(_:cellForRowAt:)方法中,所有单元格都被设置了accessoryView = switchView,因此所有行都会显示开关。只需添加条件判断,仅为目标行设置UISwitch,其他行重置accessoryView即可。

修改后的代码

import UIKit

class SettingsVC: UIViewController {
    
    var tableView = UITableView(frame: .zero, style: .insetGrouped)
    let cells = ["Change Accent Color", "Change Currency Symbol", "Vibrations"]
    let cellReuseIdentifier = "cell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createTableView()
        setTableViewDelegates()
    }
    
    func createTableView() {
        view.addSubview(tableView)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.topAnchor),
            tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
            tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
    
    func setTableViewDelegates() {
        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension SettingsVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {
            return UITableViewCell()
        }
        
        cell.textLabel?.text = cells[indexPath.row]
        
        // 仅为目标行(这里是第三行,indexPath.row == 2)添加UISwitch
        if indexPath.row == 2 {
            let switchView = UISwitch(frame: .zero)
            switchView.setOn(false, animated: true)
            // 可选:给开关添加点击事件
            switchView.addTarget(self, action: #selector(switchValueChanged(_:)), for: .valueChanged)
            cell.accessoryView = switchView
        } else {
            // 其他行清除accessoryView,避免复用单元格时残留开关
            cell.accessoryView = nil
        }
        
        return cell
    }
    
    // 可选:处理开关状态变化的方法
    @objc private func switchValueChanged(_ sender: UISwitch) {
        print("开关状态:\(sender.isOn)")
    }
}

关键说明

  1. 条件判断:通过indexPath.row == 2定位到"Vibrations"对应的行,仅为该行创建并设置UISwitch作为accessoryView。
  2. 复用重置:在else分支中将accessoryView设为nil,因为UITableView会复用单元格,如果不重置,之前显示过开关的单元格被复用时会继续显示开关,导致错误。
  3. 可选扩展:添加switchValueChanged方法可以处理开关的状态变化,根据业务需求添加逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:45:35