首页 > 解决方案 > 如果以编程方式添加,UISwitch 不会响应操作

问题描述

无法解决此问题。有这个功能:

func addSwitch(){
    switchB.setOn(true, animated: false)
    switchB.addTarget(self, action: #selector(valueChange), for:UIControl.Event.valueChanged)
    view.addSubview(switchB)
    switchB.translatesAutoresizingMaskIntoConstraints = false
    switchB.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    switchB.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -16).isActive = true
}
@objc func valueChange(mySwitch: UISwitch) {
    if mySwitch.isOn{
        switchB.onTintColor = UIColor.black
    }
    else{
        switchB.onTintColor = UIColor.white
    }
}

然后我将其添加到viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()
        addSwitch()

    }

我看到了按钮,但它不响应操作。

升级版:

class Main: UIViewController, UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource,CLLocationManagerDelegate {
    let switchB = UISwitch()
    override func viewDidLoad() {
        super.viewDidLoad()
        addSwitch()
    }

一切都在新项目中有效,但在当前 - 不。我使用谷歌地图,也许地图层有问题,但我看到了我的按钮。

UPD2:工作!(感谢 Francesco Deliro)google mapView 设置属性有一个名为 consumesGestureInView 的属性,默认设置为 true 尝试:yourMapView.settings.consumesGestureInView = false

标签: iosswiftuiswitch

解决方案


您的代码没有问题。色调颜色动作正在发挥作用。确保 switchbB 变量是正确的。

var switchbB = UISwitch()

    func addSwitch(){
            switchbB.setOn(true, animated: false)
            switchbB.addTarget(self, action: #selector(valueChange), for:UIControl.Event.valueChanged)
            view.addSubview(switchbB)
            switchbB.translatesAutoresizingMaskIntoConstraints = false
            switchbB.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
            switchbB.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -16).isActive = true
        }

  @objc func valueChange(mySwitch: UISwitch) {
            if mySwitch.isOn{
                switchbB.onTintColor = UIColor.black
            }
            else{
                switchbB.onTintColor = UIColor.white
            }
        }

推荐阅读