如何更改 UIBarButtonItem
的标题?我有以下代码,当在我的 UINavigationBar
上按下 edit 按钮时调用它。
-(void)editButtonSelected:(id)sender {
NSLog(@"edit button selected!");
if(editing) {
NSLog(@"notediting");
[super setEditing:NO animated:NO];
[tableView setEditing:NO animated:NO];
[tableView reloadData];
[rightButtonItem setTitle:@"Edit"];
[rightButtonItem setStyle:UIBarButtonItemStylePlain];
editing = false;
}
else {
NSLog(@"editing");
[super setEditing:YES animated:YES];
[tableView setEditing:YES animated:YES];
[tableView reloadData];
[rightButtonItem setTitle:@"Done"];
[rightButtonItem setStyle:UIBarButtonItemStyleDone];
editing = true;
}
}
edit 按钮正在改变颜色(因此设置样式的行有效),但是设置按钮标题的行无效。
最佳答案
我已完成以下操作以动态更改 UIBarButtonItem 的标题。在这种情况下,我没有使用 UIViewTableController,也不能使用标准的 editButton。我有一个带有 tableView 以及其他 subview 的 View ,我想模拟有限的 UIViewTableController 的行为。
- (void)InitializeNavigationItem
{
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:2];
UIBarButtonItem* barButton;
barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addNewItem:)];
barButton.style = UIBarButtonItemStyleBordered;
[array addObject:barButton];
// --------------------------------------------------------------------------------------
barButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered
target:self
action:@selector(editMode:)];
barButton.style = UIBarButtonItemStyleBordered;
barButton.possibleTitles = [NSSet setWithObjects:@"Edit", @"Done", nil];
[array addObject:barButton];
self.navigationItem.rightBarButtonItems = array;
}
- (IBAction)editMode:(UIBarButtonItem *)sender
{
if (self.orderTable.editing)
{
sender.title = @"Edit";
[self.orderTable setEditing:NO animated:YES];
}
else
{
sender.title = @"Done";
[self.orderTable setEditing:YES animated:YES];
}
}
请注意,我没有使用 UIBarButtonSystemItemEdit barButton,您不能手动更改该按钮的名称,这是有道理的。
您可能还想利用 possibleTitles 属性,以便在您更改标题时按钮不会调整大小。
如果您使用 Storyboard/XIB 来创建/设置这些按钮,请确保您要控制其标题的按钮的栏按钮项目标识符设置为自定义。
关于ios - UIBarButtonItem 更改标题不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6158169/