[Xcode 實際操做]4、經常使用控件-(6)UISwitch開關控件的使用

目錄:[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 }
相關文章
相關標籤/搜索