views:

11406

answers:

2

I'm trying to add a label to my toolbar. Button works great, however when I add the label object, it crashes. Any ideas?

UIBarButtonItem *setDateRangeButton = [[UIBarButtonItem alloc] initWithTitle:@"Set date range"
                                                                       style:UIBarButtonItemStyleBordered
                                                                      target:self
                                                                      action:@selector(setDateRangeClicked:)];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
label.text = @"test";

[toolbar setItems:[NSArray arrayWithObjects:setDateRangeButton,label, nil]];

// Add the toolbar as a subview to the navigation controller.
[self.navigationController.view addSubview:toolbar];

// Reload the table view
[self.tableView reloadData];
+15  A: 

Have a look into this

[[UIBarButtonItem alloc] initWithCustomView:yourCustomView];

Essentially every item must be a "button" but they can be instantiated with any view you require

adam
Note that if you chose to go this route you must style your label appropriately (label.backgroundColor = [UIColor clearColor], etc). You can also init a UIBarButtonItem to be styled Plain which will give you a similar look
wisequark
Thank you!I got the idea.
Boolean
+1  A: 

One of the things I'm using this trick for is to instantiate a UIActivityIndicatorView on top of the toolbar, something that otherwise wouldn't be possible. For instance here I have a toolbar with 2 UIBarButtonItems, a Flexible Space Bar Button Item, and then another UIBarButtonItem. I want to insert a UIActivityIndicatorView into the toolbar between the flexible space and the final (right-hand) button. So in my RootViewController I do the following,

- (void)viewDidLoad {
[super viewDidLoad];// Add an invisible UIActivityViewIndicator to the toolbar
UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:767];
NSArray *items = [toolbar items];

activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite]; 

NSArray *newItems = [NSArray arrayWithObjects:[items objectAtIndex:0],[items objectAtIndex:1],[items objectAtIndex:2],
      [[UIBarButtonItem alloc] initWithCustomView:activityIndicator], [items objectAtIndex:3],nil];
[toolbar setItems:newItems];}
Alasdair Allan