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];
Try this:
Note:
self.barItem
is aUIBarButtonItem
added from the object library and placed between two flexible spaces.another way is to remove the
[self.barItem setCustom:view]
line and change the parameters of thelabel
(width) so that it fills the entire toolbar and set the alignment to middle and the font by yourself in code,I found answerBot's answer very useful, but I think I found an even easier way, in Interface Builder:
plug this BarButtonItem to a property in your class (this is in Swift, but would be very similar in Obj-C):
add another property for the Label itself:
in viewDidLoad, add the following code to set the properties of your label, and add it as the customView of your BarButtonItem
To update the
UILabel
text:Result :
You have to call
lastUpdateLabel.sizetoFit()
each time you update the label textOne of the things I'm using this trick for is to instantiate a
UIActivityIndicatorView
on top of theUIToolBar
, something that otherwise wouldn't be possible. For instance here I have aUIToolBar
with 2UIBarButtonItem
, aFlexibleSpaceBarButtonItem
, and then anotherUIBarButtonItem
. I want to insert aUIActivityIndicatorView
into theUIToolBar
between the flexible space and the final (right-hand) button. So in myRootViewController
I do the following,If you want to adding a view up the toolbar view you can try this:
Similar to Matt R I used interface builder. But I wanted to have 1
UIWebView
inside instead so that i can have some text bolded and other text not (like the mail app). SoIBOutlet
html
to have a transparent background so the toolbar shines throughCode:
For those using Interface Builder to layout your
UIToolBar
, it is also possible to do this using Interface Builder alone.To add a
UILabel
to aUIToolBar
you need to add a genericUIView
object to yourUIToolBar
in IB by dragging a newUIView
object over yourUIToolBar
.IB
will automatically create aUIBarButtonItem
that will be initialized with your customUIView
. Next add aUILabel
to theUIView
and edit theUILabel
graphically to match your preferred style. You can then visually set up your fixed and/or variable spacers as desired to position yourUILabel
appropriately.You must also set the background of both the
UILabel
and theUIView
toclearColor
to get theUIToolBar
to show through correctly under theUILabel
.