How to link a boolean value to the on/off state of a UISwitch?

前端 未结 7 1511
深忆病人
深忆病人 2020-12-24 12:11

I have a UISwitch that I want to control a boolean value in a function I wrote. I looked in the UISwitch Type Reference and it listed the property

7条回答
  •  清酒与你
    2020-12-24 12:49

    Add the UISwitch Reference into ViewController.swift file.

    @IBOutlet var mySwitch: UISwitch 
    @IBOutlet var switchState: UILabel
    

    then add the target event into the viewdidload method like below

    mySwitch.addTarget(self, action: #selector(ViewController.switchIsChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
    

    When the switch is flipped the UIControlEventValueChanged event is triggered and the stateChanged method will be called.

    func switchIsChanged(mySwitch: UISwitch) {
        if mySwitch.on {
            switchState.text = "UISwitch is ON"
        } else {
            switchState.text = "UISwitch is OFF"
        }
    }
    

    Swift 3.0

    func switchIsChanged(mySwitch: UISwitch) {
        if mySwitch.isOn {
            switchState.text = "UISwitch is ON"
        } else {
            switchState.text = "UISwitch is OFF"
        }
    }
    

    Swift 4.0

    @objc func switchIsChanged(mySwitch: UISwitch) {
        if mySwitch.isOn {
            switchState.text = "UISwitch is ON"
        } else {
            switchState.text = "UISwitch is OFF"
        }
    }
    

    find brief tutorial in http://sourcefreeze.com/uiswitch-tutorial-using-swift-in-ios8/

提交回复
热议问题