Changing UIBarButtonItem title impossible?

☆樱花仙子☆ 提交于 2019-12-12 10:18:45

问题


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


来源:https://stackoverflow.com/questions/13675859/changing-uibarbuttonitem-title-impossible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!