Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set title for UIBarButtonItem?

Tags:

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 } 
like image 990
KSL Avatar asked Jan 29 '15 09:01

KSL


2 Answers

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)) 
like image 76
Kirsteins Avatar answered Sep 27 '22 17:09

Kirsteins


Swift 2 answer

You could just add the following to viewDidLoad:

// Some text self.barButtonItemClicked.title = "Right Button!" 

OR

// A Unicode Gear Symbol // See: http://graphemica.com/%E2%9A%99 self.barButtonItemClicked.title = "\u{2699}" 

The ViewController.Swift code below would set the name barButtonItemClicked you used. I used a UIBarButtonItem to show how to set the title. But it is trivial to adapt it for a function.

import UIKit  class ViewController: UIViewController {      // Please make sure the line below is properly connected to your Storyboard!     @IBOutlet weak var barButtonItemClicked: UIBarButtonItem!      override func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view, typically from a nib.         // Set the text of the NavBarButtonItem Title          self.barButtonItemClicked.title = "Right Button!"         // Gear Icon        // self.barButtonItemClicked.title = "\u{2699}"      }      override func didReceiveMemoryWarning() {         super.didReceiveMemoryWarning()         // Dispose of any resources that can be recreated.     }  } 
like image 40
rvg Avatar answered Sep 27 '22 17:09

rvg