Set Title to UIBarButtonItem

3.5k Views Asked by At

I have UIBarButtonItem and whenever I try to set title to the button, its not working.

@IBOutlet weak var barButton: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

     barButton.title = "AB"
}

But if I try to create Action of UIBarButtonItem and then do sender.setTitle() then it works. But not at viewDidLoad. I don't want to set title when user taps on the button.

4

There are 4 best solutions below

0
On

Try this instead

@IBOutlet weak var barButton: UIBarButtonItem! {
  didSet {
    barButton.title = "AB"
 }
}
1
On

If you already have an IBOutlet for the barButton, why not just set the title in the storyboard? I think this is the easiest way unless you have some other reason for doing it programmatically.

enter image description here

0
On

Change title or image and then resign it back to navigationItem:

class AnotherViewController: UIViewController {

    @IBOutlet weak var myBarButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let barButton = myBarButton
        barButton?.title = "Anther Title"
        navigationItem.rightBarButtonItem = barButton

    }
}

Apple document: https://developer.apple.com/reference/uikit/uibaritem/1616412-title

You should set this property before adding the item to a bar. The default value is nil.

0
On

When I try this, it works. Maybe there is a bug with Xcode, delete your button and connections then try again.

class ViewController: UIViewController {

   @IBOutlet weak var barButton: UIBarButtonItem!
   override func viewDidLoad() {
       super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
       barButton.title = "MyButton"
}