我正在尝试以编程方式创建一个 UISwitch(没有 IBOutlets 或 IBActions),但我似乎无法弄清楚如何让开关在按下时改变状态。我以为 ...
mySwitch.addTarget()
... 每次打开/关闭开关时都会调用它,但情况似乎并非如此。有人可以解释我做错了什么以及如何纠正这个问题。
import UIKit
import XCPlayground
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320 * 0.75, height: 568 * 0.75))
view.backgroundColor = UIColor.whiteColor()
view.layer.borderColor = UIColor.grayColor().CGColor
view.layer.borderWidth = 1
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 320 * 0.75, height: 50))
label.text = "Label"
label.textAlignment = NSTextAlignment.Center
view.addSubview(label)
func switchChanged(sender: UISwitch!) {
if sender.on == true {
label.text = "Switch is ON"
} else if sender.on == false {
label.text = "Switch is OFF"
}
}
let mySwitch = UISwitch()
mySwitch.center = view.center
mySwitch.setOn(true, animated: false)
mySwitch.onTintColor = UIColor.redColor()
mySwitch.addTarget(label, action: Selector(switchChanged(mySwitch)), forControlEvents: UIControlEvents.ValueChanged)
view.addSubview(mySwitch)
XCPlaygroundPage.currentPage.liveView = view