如果以编程方式添加,UISwitch将不响应操作

时间:2018-11-01 10:39:34

标签: ios swift 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()

    }

我看到了该按钮,但是它对操作没有响应。

UPD:

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

一切都在新项目中进行,但在当前项目中-不 我正在使用google maps,也许在地图图层中有问题,但是我看到了我的按钮。

UPD2:工作! (感谢Francesco Deliro)google mapView settings属性具有一个称为ConsumpsGestureInView的属性,默认情况下将其设置为true尝试:yourMapView.settings.consumesGestureInView = false

2 个答案:

答案 0 :(得分:0)

删除尺寸锚点。

替换

switchB.addTarget(self, action: #selector(valueChange(_:)), for:UIControl.Event.valueChanged)

@objc func valueChange(_ mySwitch: UISwitch) {
   mySwitch.onTintColor =  mySwitch.isOn ?  .black : .white
}

答案 1 :(得分:-1)

您的代码没有问题。色调颜色操作正常。确保switchbB变量是prroper。

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
            }
        }