[Xcode 实际操作]四、常用控件-(10)动作表样式警告窗口的使用

目录:[Swift]Xcode实际操作

本文将演示动作表单窗口的使用。

动作表单可以给用户展现一系列的选项,

和警告窗口不同的是,动作表单的展示形式和设备的尺寸有关。

在项目导航区,打开视图控制器的代码文件【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,  280, height: 44)
12         //设置按钮在正常状态下的标题文字
13         bt.setTitle("Question", for: .normal)
14         //为按钮绑定点击事件
15         bt.addTarget(self, action: #selector(ViewController.showActionSheet), for:.touchUpInside)
16         //设置按钮的背景颜色为浅灰色
17         bt.backgroundColor = UIColor.lightGray
18         //将按钮添加到当前视图控制器的根视图
19         self.view.addSubview(bt)
20     }
21     
22     //创建一个方法,用来响应按你的点击事件
23     @objc func showActionSheet()
24     {
25         //初始化一个警告窗口并设置窗口的标题文字和提示信息
26         //同时设置弹出窗口为东坐表样式
27         let alert = UIAlertController(title: "Information", message: "What's your favorite?", preferredStyle: UIAlertController.Style.actionSheet)
28         
29         //创建一个默认样式的按钮,作为动作表中的提示按钮,
30         //当用户点击此按钮时,在控制台打印输出日志
31         let fishing = UIAlertAction(title: "Fishing", style: UIAlertAction.Style.default, handler: {(alerts: UIAlertAction) -> Void in print("I like fishing")
32         })
33         
34         //创建一个消除样式的按钮,作为动作表中的提示按钮,
35         //当用户点击此按钮时,在控制台打印输出日志
36         let hunting = UIAlertAction(title: "Hunting", style: UIAlertAction.Style.destructive, handler: {(alerts: UIAlertAction) -> Void in print("I like hunting")
37         })
38         
39         //创建一个取消样式的按钮,作为动作表中的提示按钮,
40         //当用户点击此按钮时,在控制台打印输出日志
41         let nothing = UIAlertAction(title: "Nothing", style: UIAlertAction.Style.cancel, handler: {(alerts: UIAlertAction) -> Void in print("A Life of Nonsense.")
42         })
43         
44         //将三个按钮,依次添加到警告窗口中
45         alert.addAction(fishing)
46         alert.addAction(hunting)
47         alert.addAction(nothing)
48         
49         //在当前视图控制器中,展示提示窗口
50         self.present(alert, animated: true, completion: nil)
51     }
52 
53     override func didReceiveMemoryWarning() {
54         super.didReceiveMemoryWarning() 
55         // Dispose of any resources that can be recreated.
56     }
57 }