iOS常见问题之动态修改UINavigationController的rightBarButtonItem的title
1.初始化
在viewDidLoad里,为navigationItem添加名称为“添加分栏”的按钮
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.navigationItem.rightBarButtonItem.title = @"添加分栏"; [self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(myAction)]; }
2.试图更改按钮名称失败
-(void)onSelectionChanged:(id)selection { self.navigationItem.rightBarButtonItem.title = @"编辑"; }
3.原因分析
为何直接设置backBarButtonItem的title无效呢?
查看苹果文档UIBarButtonItem的父类UIBarItem的title属性描述:
You should set this property before adding the item to a bar. The default value is nil.故无法修改其title,只能重置这个控件本身。
4.正确代码
4.1思路一
self.navigationItem.rightBarButtonItem.title = @"编辑"; [self.navigationItem.rightBarButtonItem initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(myAction)];
4.1思路二
UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemUndo target:self action:@selector(changeWellColumnAction)]; temporaryBarButtonItem.title = @"编辑"; self.navigationItem.rightBarButtonItem = temporaryBarButtonItem; [temporaryBarButtonItem release];
5.总结
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。