为什么我不能更改UIBarButtonItem的标题?
我想改变UIBarButtonItem
的title
。
但是这个代码不工作。
- (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] }
我不知道如何解决这个问题。
请告诉我一个方法来解决这个问题。
item.title = @"new title"
应该可以工作。
像这样初始化你的UIBarButtonItem:
_smay = [[UIBarButtonItem alloc] initWithTitle:@"Your Title" style:UIBarButtonItemStyleBordered target:self action:@selector(yourMethod)]; self.navigationItem.rightBarButtonItem = _smay;
那么,如果你想改变你的代码中的其他地方的标题:
[_smay setTitle:@"Your Other Title"];
IOS 8和更高
UIBarButtonItemStyleBordered已被弃用,所以使用下面的。
[[UIBarButtonItem alloc] initWithTitle:@"Your Title" style:UIBarButtonItemStylePlain target:self action:@selector(yourMethod)];
如果你想以编程方式改变导航栏的标题的意思
UIBarButtonItem *aDoneItem = [UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit:)]; navigationController.rightBarButtonItem = aDoneItem; aDoneItem.title = @"Something";
你必须确保button被初始化。 如果它是.xib文件的一部分,请确保已将其与IBOutlet
相关联,该@property
也包含与之关联的IBOutlet
。 否则,您需要以编程方式初始化它。 另外,你应该使用方法setTitle:forState: