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)
self.view.addSubview(uiSwitch)//将开光对象添加到当前视图控制器的根视图
}
@objc func switchChanged(_ 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)//在当前视图控制器中,展示提示窗口
}