如何正确使用UISwitch?
我的代码不工作。我不知道为什么。问题是switchChanged函数的属性。如果属性为空,则代码正在工作。如何正确使用UISwitch?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect = CGRectMake(130, 100, 0, 0)
let uiSwitch = UISwitch(frame: rect)
uiSwitch.setOn(true, animated: true)
uiSwitch.addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged)
self.view.addSubview(uiSwitch)
}
func switchChanged(uiSwitch: UISwitch) {
var message = "Turn on the switch"
if uiSwitch.on {
message = "Turn off the switch"
} else {
message = "Turn on the switch"
}
let alert = UIAlertController(title: "Information", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
错误:“的libC++ abi.dylib:与类型NSException的未捕获的异常终止”
"switchChanged"
是不是正确的选择名字,你应该使用"switchChanged:"
占该参数。 switchChanged
将是一个没有参数的方法。
另外,在Swift中,您应该使用#selector(switchChanged(_:))
来代替。这将在编译过程中验证选择器的存在。
uiSwitch.addTarget(self,action:#selector(ViewController.switchChanged(_ :)),forControlEvents:UIControlEvents.ValueChanged) –
Xcode要求我在“#”之前插入“,”。 –
但“switchChanged:”正在工作!谢谢! –
您已经在标签中指出了您对Swift的使用,因此无需将其添加到标题中。 –