1. 程式人生 > >[Xcode10 實際操作]四、常用控制元件-(9)普通警告視窗的使用

[Xcode10 實際操作]四、常用控制元件-(9)普通警告視窗的使用

本文將演示警告視窗的使用方法。

警告視窗不僅可以給使用者展現提示資訊,還可以提供若干選項供使用者選擇。

在專案導航區,開啟檢視控制器的程式碼檔案【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 //首先建立一個按鈕,當點選按鈕時,彈出警告視窗。 9 let bt = UIButton(type: UIButton.ButtonType.system) 10 //設定按鈕的位置為(20,120),尺寸為(280,44) 11 bt.frame = CGRect(x: 20, y: 120, width: 280, height: 44) 12 //接著設定按鈕在正常狀態下的標題文字 13 bt.setTitle("Question", for: .normal) 14 //為按鈕繫結點選事件
15 bt.addTarget(self, action: #selector(ViewController.showAlert), for: .touchUpInside) 16 //設定按鈕的背景顏色為淺灰色 17 bt.backgroundColor = UIColor.lightGray 18 //將按鈕新增到當前檢視控制器的根檢視 19 self.view.addSubview(bt) 20 } 21 22 //建立一個方法,用來響應按鈕的點選事件 23 @objc func showAlert()
24 { 25 //初始化一個警告視窗並設定視窗的標題文字和提示資訊 26 let alert = UIAlertController(title: "Information", message: "Are you a student?", preferredStyle: UIAlertController.Style.alert) 27 28 //建立一個按鈕,作為提示視窗中的提示按鈕。 29 //當用戶點選此按鈕時,在控制檯列印輸出日誌 30 let yes = UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {(alerts: UIAlertAction) -> Void in print("Yes, I'm a student.")}) 31 32 //再建立一個按鈕,作為提示視窗中的提示按鈕。 33 //當用戶點選此按鈕時,在控制檯列印輸出日誌 34 let no = UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: {(alerts: UIAlertAction) -> Void in print("No, I'm not a student.")}) 35 36 //將兩個按鈕,分別新增到提示視窗 37 alert.addAction(yes) 38 alert.addAction(no) 39 40 //在當前檢視控制器中,展示提示視窗 41 self.present(alert, animated: true, completion: nil) 42 } 43 44 override func didReceiveMemoryWarning() { 45 super.didReceiveMemoryWarning() 46 // Dispose of any resources that can be recreated. 47 } 48 }