Changing UIBarButtonItem title impossible?

2019-06-04 23:03发布

问题:

Silly thing, I am trying to change the title on a UIBarButtonItem if a certain condition in a for-loop is met. However I'm having trouble.

I've tried

self.barButtonItem.title=@"NewTitle"

and

[self.barButtonItem setTitle:@"New Title"];

I even did a setNeedsDisplay on the view afterwards without any luck. By the way, yes I am getting the old array of buttons from self.navigationBar.items, removing the old button, and setting the new one.

If I change the screen orientation (flip ipad), the button title does change. But otherwise, it stays the same.

Am I missing something?

回答1:

Problem

If u explore the documentation, apple says :

"You should set this property before adding the item to a bar."

For that reason,

cancel_btn.title = "something"  // It does not work !

Because u already set the item to the bar.

Solution

//
let theTitle = "something"

//
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: theTitle, style: 
UIBarButtonItemStyle.plain, target: self, action: 
#selector(cancelAction))

Now u set the title before adding the item to the bar.



回答2:

I make use of the possibleTitles property of UIBarButtonItem for this.

Try this when you create the button:

self.barButtonItem = [[UIBarButtonItem alloc] init...];
self.barButtonItem.possibleTitles = [NSSet setWithObjects:@"Title 1", @"Title 2", nil];

then later, to change the title, do:

self.barButtonItem.title = @"Title X"; // must be one of the possibleTitles