Why can't I change UIBarButtonItem's title

2019-06-20 01:17发布

I want to change UIBarButtonItem's title.

But this code is not working.

- (void)viewDidLoad {
    ...        
    [self smay];
}

- (void)smay {
    ...

    AppDelegate *apd = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSString *SmayUse = [NSString stringWithFormat:@"%d月%d日",
                           apd.newyear,apd.newmonth];
    [_smay setTitle:SmayUse]
}

I don't know how to solve this problem.

Please tell me a way to solve this problem.

4条回答
放荡不羁爱自由
2楼-- · 2019-06-20 01:47

item.title = @"new title" should work.

查看更多
爷的心禁止访问
3楼-- · 2019-06-20 01:48

if u want to change the title of navigation bar programmatically means

UIBarButtonItem *aDoneItem = [UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered
   target:self
   action:@selector(toggleEdit:)];

navigationController.rightBarButtonItem = aDoneItem;

aDoneItem.title = @"Something";
查看更多
孤傲高冷的网名
4楼-- · 2019-06-20 01:52

You have to make sure the button is initialized. If it is part of a .xib file, make sure you have it linked up with your @property that has also an IBOutlet associated with it. Otherwise you need to initialize it programatically. Also, you should use the method setTitle:forState:.

查看更多
在下西门庆
5楼-- · 2019-06-20 02:07

Initialize your UIBarButtonItem like this:

_smay = [[UIBarButtonItem alloc] initWithTitle:@"Your Title" 
             style:UIBarButtonItemStyleBordered 
             target:self action:@selector(yourMethod)];

self.navigationItem.rightBarButtonItem = _smay;

Then, if you want to change the title somewhere else in your code:

[_smay setTitle:@"Your Other Title"];

IOS 8 and higher

UIBarButtonItemStyleBordered is deprecated, so use the below.

[[UIBarButtonItem alloc] initWithTitle:@"Your Title" 
                 style:UIBarButtonItemStylePlain
                 target:self action:@selector(yourMethod)];
查看更多
登录 后发表回答