swift Swift - 以编程方式添加导航栏标题和按钮

Posted

tags:

篇首语:本文由小常识网(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 - 以编程方式添加导航栏标题和按钮的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式将约束添加到导航栏 Swift

Swift iOS以编程方式在导航栏下方设置scrollView约束

(Swift) 以编程方式在 UITableViewController 上方添加 UIView

Swift:以编程方式嵌入标签栏控制器后,导航栏消失

Swift-以编程方式导航控制器和标签栏控制器

在 rootView Swift 3.0 之后以编程方式在 ViewControllers 添加栏按钮项