UINavigationItem titleView position

前端 未结 7 764
长发绾君心
长发绾君心 2021-02-13 03:45

I\'m using UINavigationItem\'s titleView property to set a custom UILabel with my desired font size/color. Here\'s my code:

self.headerLabel = [[UILabel alloc] i         


        
7条回答
  •  长发绾君心
    2021-02-13 04:10

    I've used custom title labels for my nav bars in every app I have in the app store. I've tested many different ways of doing so and by far the easiest way to use a custom label in a navigation bar is to completely ignore titleView and insert your label directly into navigationController.view.

    With this approach, it's easy to have the title label's frame always match the navigationBar's frame -- even if you are using a custom navBar with a non-standard size.

    - (void)viewDidLoad {
       [self.navigationController.view addSubview:self.titleLabel];
       [super viewDidLoad];
    }
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:
                 (UIInterfaceOrientation)interfaceOrientation {
       return YES;
    }
    
    - (void)didRotateFromInterfaceOrientation:
                 (UIInterfaceOrientation)fromInterfaceOrientation {
       [self frameTitleLabel];
    }
    
    - (UILabel *) titleLabel {
       if (!titleLabel) {
          titleLabel = [[UILabel alloc]           
              initWithFrame:self.navigationController.navigationBar.frame];
    
           titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
           titleLabel.text = NSLocalizedString(@"Custom Title", nil);
           titleLabel.textAlignment = UITextAlignmentCenter;
           titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
       }
       return titleLabel;
    }
    
    - (void) frameTitleLabel {
       self.titleLabel.frame = self.navigationController.navigationBar.frame;
    }
    

    The one caveat to this approach is that your title can flow over the top of any buttons you have in the navBar if you aren't careful and set the title to be too long. But, IMO, that is a lot less problematical to deal with than 1) The title not centering correctly when you have a rightBarButton or 2) The title not appearing if you have a leftBarButton.

提交回复
热议问题