篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift - 以编程方式添加导航栏标题和按钮相关的知识,希望对你有一定的参考价值。
See: https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-bar-button-to-a-navigation-bar
If you build a stack of view controllers with a navigation controller, but without embedding a VC in the NC then you have to add the navigation bar and buttons programmatically to every VC.
01. Example with a title, left and right button
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = "Profile Settings"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
}
@objc func addTapped() {
//Do something if the bar buttons are tapped
}
02. Example with a title and two buttons on the right:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Third VC"
let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
let play = UIBarButtonItem(title: "Play", style: .plain, target: self, action: #selector(addTapped))
self.navigationItem.rightBarButtonItems = [add, play]
}
@objc func addTapped() {
//Do something if the bar buttons are tapped
}
以上是关于swift Swift - 以编程方式添加导航栏标题和按钮的主要内容,如果未能解决你的问题,请参考以下文章