How do I set title for UIBarButtonItem?

KSL picture KSL · Jan 29, 2015 · Viewed 29.7k times · Source

I'm a beginner iPhone developer.

How can I programmatically set the title for the UIBarButtonItem?

My code is the following:

self.navigationItem.rightBarButtonItems =
    UIBarButtonItem(
        barButtonSystemItem: .Cancel, target: self,
        action: "barButtonItemClicked:")

@IBAction func barButtonItemClicked(sender: UIBarButtonItem) {
    //print something
}

Answer

Kirsteins picture Kirsteins · Jan 29, 2015

Use different initialiser that allows you to specify the title:

UIBarButtonItem(title: "title", style: .Plain, target: self, action: "barButtonItemClicked:")

Swift 3.1 Update

UIBarButtonItem(title: "title", style: .plain, target: self, action: #selector(barButtonItemClicked))