[Xcode10 实际操作]三、视图控制器-(7)UINavigationController自定义导航按钮

本文将演示设置导航按钮的样式,以及设置导航标题区域的样式。

 1 import UIKit
 2 
 3 class FirstSubViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7 
 8         // Do any additional setup after loading the view.
 9         self.title = "First Page"
10         self.view.backgroundColor = UIColor.brown
11         
12         //实例化一个工具条按钮对象,它将作为新的导航按钮
13         let leftBar = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.refresh, target: self, action: #selector(FirstSubViewController.refresh))
14         //将导航栏左侧按钮,设置为新建的工具条按钮对象
15         self.navigationItem.leftBarButtonItem = leftBar
16         
17         //同样为导航栏的右侧导航按钮,设置新的样式
18         let rightBar = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.save, target: self, action: #selector(FirstSubViewController.save))
19         //将导航栏的右侧按钮,设置为新建的工具条按钮对象
20         self.navigationItem.rightBarButtonItem = rightBar
21         
22         //新建一个标签对象,它将显示标题区
23         let label = UILabel(frame: CGRect(x: 0, y: 0, width: 180, height: 30))
24         //设置标签对象的文字内容
25         label.text = "Happy Day"
26         //将标签对象的文字对齐方式,设置为居中对齐。
27         label.textAlignment = NSTextAlignment.center
28         //将标签视图对象,设置为导航栏的标题区
29         self.navigationItem.titleView = label
30     }
31     
32     //创建左侧导航按钮的点击事件
33     @objc func refresh()
34     {
35         //创建一个警告弹出窗口
36         let alert = UIAlertController(title: "Infomation", message: "Refresh my feeling.", preferredStyle: UIAlertController.Style.alert)
37         //创建一个按钮,作为提示窗口中的【确定】按钮,
38         //当用户点击该按钮时,将关闭提示窗口
39         let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
40         //将确定按钮,添加到提示窗口中
41         alert.addAction(action)
42         //在当前视图控制器中,展示提示窗口
43         self.present(alert, animated: true, completion: nil)
44     }
45     
46     //创建右侧导航按钮的点击事件
47     @objc func save()
48     {
49         //当用户点击按钮时,在控制台打印输出日志
50         print("Saving...")
51     }
52     
53     override func didReceiveMemoryWarning() {
54         super.didReceiveMemoryWarning()
55         // Dispose of any resources that can be recreated.
56     }
57 }

猜你喜欢

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