如何在单击按钮时更改UIBarButtonItem的标题 - iPhone

时间:2012-06-15 19:54:20

标签: ios ios5 uibarbuttonitem navigationitem

我正在尝试在单击按钮时更改UIBarButtonItem的标题。这是我的代码......但它不起作用。

UIBarButtonItem * btnleft1 = [[UIBarButtonItem alloc] initWithTitle:@"Test2" 
                                                      style:UIBarButtonItemStyleDone 
                                                      target:self
                                                      action:@selector(TestingThis:)];

self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:btn, btnleft, btnleft1, nil];

- (void)TestingThis:(id)sender {
    if (self.navigationItem.rightBarButtonItem.title == @"Test2") {
        self.navigationItem.rightBarButtonItem.title = @"Done";
    }
    else
    {
        self.navigationItem.rightBarButtonItem.title = @"Test2";
    }
}

这就是我正在使用的代码。请记住,按钮“btnleft1”在rightBarButtonItem“S”中,而不在rightBarButtonItem中。如果我将它更改为rightbarbuttonitems.title ...它会给我一个错误。

2 个答案:

答案 0 :(得分:1)

迟到的答案,但为了将来参考,您可以使用自定义按钮执行此操作:

      CGRect frame = CGRectMake(10, 6, 60, 30);
      UIButton *customButton = [[UIButton alloc] initWithFrame:frame];
      [customButton setTitle:@"Done" forState:UIControlStateNormal];
      [customButton setTitle:@"Undone" forState:UIControlStateSelected];
      [customButton addTarget:self action:@selector(selectDoneClicked:) forControlEvents:UIControlEventTouchUpInside];
      UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:customButton ];
      [self.navigationItem setLeftBarButtonItem:leftButton];

答案 1 :(得分:0)

尝试明确设置标题。 您可以使用代码执行此操作:[(UIBarButtonItem *)item setTitle:@"someText"];
这是一个有用的链接:Change the text of a UILabel (UIBarButtonItem) on a toolbar programmatically
希望这有帮助!