Add UILabel to UIToolbar

By July 24, 2012Blog

Had the need to show the datetime in the toolbar next to the touch button. Just adding the UILabel as subview to the UIToolbar makes the app to crash. But there is a solution:

 

1
2
3
4
5
6
7
8
9
UILabel* timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 240, 20)];
timeLabel.backgroundColor = [UIColor clearColor];
timeLabel.textColor = [UIColor whiteColor];
 
// add your text here, using NSDateFormatter for example
timeLabel.text = @""; 
 
// create the bar button item where we specify the label as a view to use to init with     
UIBarButtonItem *dateTimeText = [[UIBarButtonItem alloc] initWithCustomView:timeLabel];

 

Happy coding!