[Xcode10 实际操作]四、常用控件-(1)UIButton控件的使用

本文将演示按钮控件的使用,按钮是用户界面中最常见的交互控件

在项目导航区,打开视图控制器的代码文件【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 bt1 = UIButton(type: UIButton.ButtonType.infoDark)
10         //设置按钮的位置为(130,80),尺寸为(40,40)
11         bt1.frame = CGRect(x: 130, y: 80, width: 40, height: 40)
12         
13         //接着创建一个普通的圆角按钮
14         let bt2 = UIButton(type: UIButton.ButtonType.roundedRect)
15         //设置按钮的位置为(80,180),尺寸为(150,44)
16         bt2.frame = CGRect(x: 80, y: 180, width: 150, height: 44)
17         //设置按钮的背景颜色为紫色
18         bt2.backgroundColor = UIColor.purple
19         //设置按钮的前景颜色为黄色
20         bt2.tintColor = UIColor.yellow
21         //继续设置按钮的标题文字
22         bt2.setTitle("Tap Me", for: UIControl.State())
23         //给按钮绑定点击的动作
24         bt2.addTarget(self, action: #selector(ViewController.buttonTap(_:)), for: UIControl.Event.touchUpInside)
25         
26         //再创建一个圆角按钮
27         let bt3 = UIButton(type: UIButton.ButtonType.roundedRect)
28         //设置按钮的背景颜色为棕色
29         bt3.backgroundColor = UIColor.brown
30         //设置按钮的前景颜色为白色
31         bt3.tintColor = UIColor.white
32         //设置按钮的标题文字
33         bt3.setTitle("Tap Me", for: UIControl.State())
34         //设置按钮的位置为(80,280),尺寸为(150,44)
35         bt3.frame = CGRect(x: 80, y: 280, width: 150, height: 44)
36         //给按钮添加边框效果
37         bt3.layer.masksToBounds = true
38         //设置按钮层的圆角半径为10
39         bt3.layer.cornerRadius = 10
40         //设置按钮层边框的宽度为4
41         bt3.layer.borderWidth = 4
42         //设置按钮层边框的颜色为浅灰色
43         bt3.layer.borderColor = UIColor.lightGray.cgColor
44         
45         //将三个按钮,分别添加到当前视图控制器的根视图
46         self.view.addSubview(bt1)
47         self.view.addSubview(bt2)
48         self.view.addSubview(bt3)
49     }
50     
51     //添加一个方法,用来响应按你的点击事件
52     @objc func buttonTap(_ button:UIButton)
53     {
54         //创建一个警告弹出窗口,当按钮被点击时,弹出此窗口,
55         let alert = UIAlertController(title: "Information", message: "UIButton Event.", preferredStyle: UIAlertController.Style.alert)
56         //创建一个按钮,作为提示窗口中的【确定】按钮,当用户点击该按钮时,将关闭提示窗口。
57         let OKAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
58         //将确定按钮,添加到提示窗口中
59         alert.addAction(OKAction)
60         //在当前视图控制器中,展示提示窗口。
61         self.present(alert, animated: true, completion: nil)
62     }
63 
64     override func didReceiveMemoryWarning() {
65         super.didReceiveMemoryWarning()
66     }
67 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10011510.html