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

UISwitch绑定的Target未触发问题求助

解决UISwitch切换无响应的问题

嘿,我帮你找到了问题所在,咱们一步步来修复它:

核心问题:初始化闭包中使用self无效

你在创建privateSwitch的闭包中直接调用addTarget(self, ...),但这个闭包是在PrivateCell实例完全初始化之前执行的,此时self还不是一个有效的实例,所以target没有正确绑定到cell上,导致开关切换时不会触发switchToggled方法。

另外还有个小细节:switchToggled里的判断逻辑反了,开关开启时的打印内容搞反啦。

修正后的代码

import Foundation 
import UIKit 

class PrivateCell: UITableViewCell { 
    var stackView: UIStackView? 
    
    let switchStatementLabel : UILabel = { 
        let switchStatementLabel = UILabel() 
        switchStatementLabel.textAlignment = .justified 
        switchStatementLabel.text = "Make Profile Private" 
        return switchStatementLabel 
    }() 
    
    let privateSwitch : UISwitch = { 
        let privateSwitch = UISwitch(frame: CGRect(x: 0, y: 0, width: 70, height: 70)) 
        privateSwitch.isOn = false 
        privateSwitch.onTintColor = UIColor.rgb(red: 44, green: 152, blue: 229) 
        // 移除闭包内的addTarget调用,移到实例初始化完成后执行
        return privateSwitch 
    }() 
    
    @objc func switchToggled(_ sender: UISwitch) { 
        // 修正判断逻辑,同时直接使用sender更严谨
        if sender.isOn { 
            print("switch turned on") 
        } else { 
            print("switch turned off") 
        } 
    } 
    
    @objc func setupViews(){ 
        backgroundColor = .white 
        stackView = UIStackView(arrangedSubviews: [ switchStatementLabel, privateSwitch]) 
        stackView?.axis = .horizontal 
        stackView?.distribution = .equalSpacing 
        
        // 在这里添加target,此时self已经是完全初始化后的有效实例
        privateSwitch.addTarget(self, action: #selector(switchToggled(_:)), for: .valueChanged)
        
        if let firstStackView = stackView{ 
            self.addSubview(firstStackView) 
            firstStackView.snp.makeConstraints { (make) in 
                make.edges.equalTo(self).inset(10) 
            } 
        } 
    } 
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
        super.init(style: style, reuseIdentifier: reuseIdentifier) 
        setupViews() 
    } 
    
    required init?(coder aDecoder: NSCoder) { 
        fatalError("init(coder:) has not been implemented") 
    } 
}

关键修改点

  • 将addTarget调用从privateSwitch的初始化闭包中移到setupViews方法里,确保self是已经完成初始化的有效实例,target能正确绑定。
  • 把switchToggled里的判断对象改为sender(触发事件的开关本身),避免直接访问实例变量可能出现的问题,同时修正了打印内容的逻辑。

这样修改后,你的开关切换时应该就能正常触发方法并打印正确的内容啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:39:53