目录:[Swift]Xcode实际操做html
本文将演示开关控件的基本用法。swift
开关控件有两个互斥的选项,它是用来打开或关闭选项的控件。ide
在项目导航区,打开视图控制器的代码文件【ViewController.swift】post
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view, typically from a nib. 8 //建立一个位置在(130,100),尺寸为(0,0)的显示区域 9 let rect = CGRect(x: 130, y: 100, width: 0, height: 0) 10 //初始化开关对象,并指定其位置和尺寸 11 let uiSwitch = UISwitch(frame: rect) 12 //设置开关对象的默认状态为选中 13 uiSwitch.setOn(true, animated: true) 14 //给开关对象,添加状态变化事件 15 uiSwitch.addTarget(self, action: #selector(ViewController.switchChanged(_:)), for: UIControl.Event.valueChanged) 16 17 //将开关对象,添加到当前视图控制器的根视图 18 self.view.addSubview(uiSwitch) 19 } 20 21 //添加一个方法,用来处理开关事件 22 @objc func switchChanged(_ uiSwitch:UISwitch) 23 { 24 //建立一个字符串,用来标识开关的状态 25 var message = "Turn on the switch." 26 //获取开关对象的状态,并根据状态,设置不一样的文字内容 27 if(!uiSwitch.isOn) 28 { 29 message = "Turn off the switch." 30 } 31 32 //建立一个信息提示窗口,并设置其显示的内容 33 let alert = UIAlertController(title: "Information", message: message, preferredStyle: UIAlertController.Style.alert) 34 //建立一个按钮,做为提示窗口中的【肯定】按钮,当用户点击该按钮时,将关闭提示窗口。 35 let OKAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) 36 //将肯定按钮,添加到提示窗口中 37 alert.addAction(OKAction) 38 //在当前视图控制器中,展现提示窗口 39 self.present(alert, animated: true, completion: nil) 40 } 41 42 override func didReceiveMemoryWarning() { 43 super.didReceiveMemoryWarning() 44 // Dispose of any resources that can be recreated. 45 } 46 }