Utku Dalmaz Utku Dalmaz - 2 years ago 285
Swift Question

Change title of a navigation bar button item

let button = UIButton()
button.setImage(UIImage(named: "coin_icon"), forState: UIControlState.Normal)
button.addTarget(self, action:#selector(Profile.goCoin), forControlEvents: UIControlEvents.TouchDragInside)
button.frame=CGRectMake(0, 0, 30, 30)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton

My code is this to add a bar button on navigation bar.

However, i need to change the title of button in a function

func changetitle() {
self.navigationItem.rightBarButtonItem?.title = "Change"

I tried this one but didn't work.

How can i change the title of this button?

Answer Source

You need to access the UIButton from the UIBarButtonItem and change the title of the UIButton.

I don't know Swift very well so the following is only a rough outline but it should give you an idea:

func changetitle() {
    let item = self.navigationItem.rightBarButtonItem
    let button = item!.customView as! UIButton
    button.setTitle("Change" forState:.Normal)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download