1. 程式人生 > >[Xcode10 實際操作]四、常用控制元件-(6)UISwitch開關控制元件的使用

[Xcode10 實際操作]四、常用控制元件-(6)UISwitch開關控制元件的使用

本文將演示開關控制元件的基本用法。

開關控制元件有兩個互斥的選項,它是用來開啟或關閉選項的控制元件。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 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 }