导航栏样式
创建导航控制器
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let viewContorller = FirstSubViewController()
//将导航视图控制器对像作为当前窗口的根视图控制器
let navigationController = UINavigationController(rootViewController: viewContorller)
self.window?.rootViewController = navigationController
return true
}
在视图将要显示时
@objc override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 设置导航栏提示文字
self.navigationItem.prompt = "Loading..."
// 设置导航栏背景是否透明
self.navigationController?.navigationBar.isTranslucent = false
// 设置系统样式
self.navigationController?.navigationBar.barStyle = UIBarStyle.black
// 设置导航按钮的前景颜色
self.navigationController?.navigationBar.tintColor = UIColor.orange
}
自定义导航按钮
// 实例化一个工具条导航按钮
let leftBar = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: #selector(FirstSubViewController.refresh))
// 将导航栏左侧按钮设置为新建的工具条按钮对象
self.navigationItem.leftBarButtonItem = leftBar
let rightBar = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.save, target: self, action: #selector(FirstSubViewController.save))
self.navigationItem.rightBarButtonItem = rightBar
// 新建一个标签对像,它将显示标题区的标题文字
let lable = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
// 设置文字内容
lable.text = "Happy day"
// 设置文字居中对齐
lable.textAlignment = NSTextAlignment.center
// 将标签视图对象,设置为导航栏的标题区
self.navigationItem.titleView = lable
// 左侧按钮的点击事件
@objc func refresh(){
let alert = UIAlertController(title: "Information", message: "Refresh", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
@objc func save(){
print("Saving...")
}