MichaelD
MichaelD

Reputation: 31

How to change Title of UIBarButtonItem when button is clicked - iPhone

I'm trying to change the title of UIBarButtonItem when button is clicked. Here's the code that I have... but it doesn't work.

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";
    }
}

So that's the code that I'm using. Please keep in mind that button "btnleft1" is in rightBarButtonItem"S" and not in rightBarButtonItem. If i change it to rightbarbuttonitems.title... it gives me an error.

Upvotes: 1

Views: 5812

Answers (2)

Zeev Vax
Zeev Vax

Reputation: 924

Late answer but for future reference, you can use custom button to do this :

      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];

Upvotes: 1

waylonion
waylonion

Reputation: 6976

Try setting the title explicitly. You can do this with code:[(UIBarButtonItem *)item setTitle:@"someText"];
Here's a helpful link: Change the text of a UILabel (UIBarButtonItem) on a toolbar programmatically
Hope this helped!

Upvotes: 0

Related Questions