override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect = CGRect(x: 130, y: 100, width: 0, height: 0)
let uiSwitch = UISwitch(frame:rect)
// 初始化开关对象
uiSwitch.setOn(true, animated: true)
// 设置开关对象的默认状态为选中
uiSwitch.addTarget(self, action:#selector(ViewController.switchChanged(_:)), for: UIControlEvents.valueChanged)
// 错误提示:Type 'ViewController' has no member 'switchChanged'
// 给开关对象,添加状态变化事件
self.view.addSubview(uiSwitch)
// 将开关对象添加到当前根视图
}
@objc func switchChanged(uiSwitch:UISwitch)
//解决办法是修改成:(_ uiSwitch:UISwitch),uiSwitch前面补上 _,表示省略方法的默认外部參数名
{
// 添加一个方法,用来处理开关事件
var message = "Turn on the switch"
// 创建一个字符串,用来标识开关的状态
if(!uiSwitch.isOn)
{
// 获取当前开关的状态,并根据状态设置不同的文字内容
message = "Turn off 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.present(alert, animated: true, completion: nil)
}