Swift 3.0 Adding a Right Button to Navigation Bar

2019-02-06 08:11发布

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 button. So far I have,

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

override func viewDidLoad() {
    super.viewDidLoad()

    let boool = true
    if boool {
        self.navigationItem.rightBarButtonItem = self.addButton
    }
    else {
        self.navigationItem.rightBarButtonItem = nil
    }
}

func addTapped(sender: AnyObject) {
    print("hjxdbsdhjbv")
}

I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.

4条回答
Summer. ? 凉城
2楼-- · 2019-02-06 08:37

Firstly, you need to connect you navigation bar to an IBOutlet so that you can refer to it in your code. After that, this code should work:

    let navigationItem = UINavigationItem(title: "Title")
    navigationItem.rightBarButtonItem = self.addButton
    navigationItem.hidesBackButton = true
    self.navigationBar.pushItem(navigationItem, animated: false)
查看更多
冷血范
3楼-- · 2019-02-06 08:52

You say you added a UINavigationBar to your view controller via storyboard, but looking at the code you provided there is no outlet connection to your navigation bar in IB.

In order to access self.navigationItem your view controller must be embedded in a UINavigationController or be part of a hierarchy which is. Unless you have a need for a custom navigation bar on an individual view controller, I suggest removing that from Interface Builder, then making sure either the view controller in question is embedded in a UINavigationController or it is being pushed onto the navigation stack from another controller which is embedded in a navigation controller and then you should see your UIBarButtonItem.

查看更多
Deceive 欺骗
4楼-- · 2019-02-06 08:54
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "EditImage"), style: .done, target: self, action: #selector(ViewController.call_Method))

self.navigationItem.rightBarButtonItem = rightBarButtonItem
查看更多
\"骚年 ilove
5楼-- · 2019-02-06 09:02

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

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))
查看更多
登录 后发表回答