Search code examples
iosuinavigationbaruinavigationitem

Set a navigation button for the title of a UINavigationBar


I want to make a standard navigation bar button for my bar's title. I can set a custom view. In the sample below, I've done this with a UILabel. But I don't see how to make a standard navigation button.

-(void) setTitleButtonWithText: (NSString*) text {
    self.title = text;
    UIFont* font = [UIFont boldSystemFontOfSize:18];
    CGSize size = [text sizeWithFont:font];
    size.width+=6;
    size.height+=6;
    UILabel* titleLabel = [[UILabel alloc]init];
    CGRect frame = CGRectZero;
    frame.size = size;
    self.navigationItem.titleView = titleLabel;
    titleLabel.frame = frame;
    titleLabel.textColor = [UIColor redColor];
    titleLabel.text = text;
    titleLabel.font = font;
}

enter image description here


Solution

  • titleView is a UIView property, so since UIBarButtonItem is not a UIView it cant be used here, as an alternative you could try making a UIButton with the same style and set that as the titleView