UINavigationBar title

2019-02-19 08:50发布

I am trying to use a UILabel to replace the title at the UINavigationBar, the code is as follows:

UINavigationBar *bar = [self.navigationController navigationBar];
    [bar setBackgroundColor:[UIColor blackColor]];

    UILabel * nav_title = [[UILabel alloc] initWithFrame:CGRectMake(80, 2, 220, 25)];
    nav_title.font = [UIFont fontWithName:@"Arial-BoldMT" size:18];
    nav_title.textColor = [UIColor whiteColor];
    nav_title.adjustsFontSizeToFitWidth = YES;
    nav_title.text = title;
    nav_title.backgroundColor = [UIColor clearColor];
    [bar addSubview:nav_title];
    [nav_title release];

The problem is that, how do I remove the original title of the bar? I didn't declare any self.title = @"title", but it always shows it there:

enter image description here

If I do self.title = nil, then everything is gone... How do eliminate this mysterious title from the navbar and just use the UILabel I created.

3条回答
姐就是有狂的资本
2楼-- · 2019-02-19 09:34

Use this:

  UILabel *label = [[UILabel alloc]init];
  [label setBackgroundColor:[UIColor clearColor]];
  [label setTextColor:[UIColor whiteColor]];
  [label setText:self.title];
  label.adjustsFontSizeToFitWidth=YES;
  label.lineBreakMode=UILineBreakModeWordWrap;
  label.numberOfLines=0;
  [label setFont:[UIFont boldSystemFontOfSize:16.0]];
  [self.navigationController.navigationBar.topItem setTitleView:label];
  [label release];

Hope this will help u..!
查看更多
趁早两清
3楼-- · 2019-02-19 09:44

Why don't you just do self.title = @""?

EDIT: Try this?

UINavigationBar *bar = [self.navigationController navigationBar];
[bar setBackgroundColor:[UIColor blackColor]];

UILabel * nav_title = [[UILabel alloc] initWithFrame:CGRectMake(80, 2, 220, 25)];
nav_title.font = [UIFont fontWithName:@"Arial-BoldMT" size:18];
nav_title.textColor = [UIColor whiteColor];
nav_title.adjustsFontSizeToFitWidth = YES;
nav_title.text = title;
self.title = @"";
nav_title.backgroundColor = [UIColor clearColor];
[bar addSubview:nav_title];
[nav_title release];
查看更多
疯言疯语
4楼-- · 2019-02-19 09:46

Use self.navigationItem.titleView = nav_title; instead of adding your label as a subview.

查看更多
登录 后发表回答