Search code examples
objective-ctextuinavigationcontrolleruilabeluitoolbar

UILabel on a UIToolbar (programmatically) doesn't display the label


I have the following code which is in -viewDidLoad: :

self.navigationController.toolbarHidden = NO;

UIBarButtonItem *shareButton = [[UIBarButtonItem alloc]    initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(sendEmail:)];

    UIBarButtonItem *spacer1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0 , 25, self.view.frame.size.width, 21.0f)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.text = @"text-here";
    label.userInteractionEnabled = NO;
    label.font = [UIFont systemFontOfSize:18.0];
    label.textAlignment = NSTextAlignmentCenter;

    UIBarButtonItem *labelItem = [[UIBarButtonItem alloc] initWithCustomView:label];

    self.navigationController.toolbarItems = [NSArray arrayWithObjects:shareButton, spacer1, labelItem, nil];

However, when I load the app, the toolbar ONLY displays the shareButton, which is linked to sharing the contents of the app through e-mail. The label doesn't appear (and I want it to). I've basically copied this exact code from other questions asked on stackoverflow, and everywhere I look is the same answer...is there something different about this?

I assume that since the share button works, the toolbar works fine. Other answers to questions like mine have produced the [self.navigationController.view addSubview:toolbarObj];, but I just used the toolbar integrated with the navigation controller.

The spacer...well, I don't exactly know how much the spacer does for me at this point. Right now, if I understand it right, the spacer will push my label item to the far right, correct? Wouldn't it space out the objects evenly? I would love to have the label in the center of the toolbar.

Help and an explanation would be greatly appreciated.


Solution

  • When I run your code it doesn't show either the label or the button. If I make the change below, they both appear:

    Change:

    self.navigationController.toolbarItems = [NSArray arrayWithObjects:shareButton, spacer1, labelItem, nil];
    

    to:

    self.toolbarItems = [NSArray arrayWithObjects:shareButton, spacer1, labelItem, nil];
    

    If you want your label in the middle, make it smaller (I just divided the view width by 2) and add a second spacer on the other side of it:

    self.toolbarItems = [NSArray arrayWithObjects:shareButton, spacer1, labelItem, spacer2, nil];