Reputation: 36148
I'd like to put dynamic text in a bar button item similar to what the new york times does with their number of comments as seen in the picture below.
Any thoughts on how i'd go about achieving this functionality?
Upvotes: 0
Views: 663
Reputation: 41
Create a UIButton and assign it to your navigation bar right bar button Item.change the text of button whenever there is an update.I created a sample project with Navigation Controller and a custom button on top of the navigation bar and button to test that functionality
//Create a button and assign it as rightbarbutton Item.
self.customButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 40)];
self.customButton.titleLabel.textColor=[UIColor whiteColor];
[self.customButton setTitle:@"0" forState:UIControlStateNormal];
self.customButton.backgroundColor=[UIColor blueColor];
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:self.customButton];
//Display some random number on navigation bar button
NSString *randomNumber=[NSString stringWithFormat:@"%u",arc4random_uniform(1000)];
[self.customButton setTitle:randomNumber forState:UIControlStateNormal];
You can download the sample project from here
Upvotes: 0
Reputation: 31282
I think the key is the - initWithCustomView: method of UIBarButtonItem
.
Here is the pseudo code, modify it according to your needs:
UICustomViewController *customVC = [[UICustomViewController alloc] initWithNibName:@"UICustomViewController" bundle:nil];
[customVC loadView]; //load the views, so your views won't be nil
[customVC updateText];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customVC.view];
[[self navigationItem] setRightBarButtonItem:barButtonItem];
Upvotes: 1