Swift 3.0 Adding a Right Button to Navigation Bar

前端 未结 6 972
夕颜
夕颜 2020-12-29 04:00

I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the butto

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 04:13

    It’s simple. Put this line of code to the viewDidLoad:

    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))
    

    Updated for Swift 4 or later:

    A custom function:

    @objc func action(sender: UIBarButtonItem) {
        // Function body goes here
    }
    

    (Custom) Right bar button item:

    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))
    

    (Custom) Left bar button item:

    self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))
    

    Also you can add a system bar button items something like this: UIBarButtonItem.SystemItem Defines system-supplied images for bar button items: .add, .done, .cancel, .edit, .save, .compose, .reply, .organize and more.

    (System) Right bar button item:

    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))
    

    (System) Left bar button item:

    self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))
    

提交回复
热议问题