简体   繁体   中英

Issue with UINavigationBar title alignment

I have an issue changing the font for the Title in my navigation controller.

Here is my code (from my subclass of UINavigationController):

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSDictionary * attributes = @{UITextAttributeTextColor  :[UIColor whiteColor],
                                  UITextAttributeFont       :[UIFont fontWithName:@"Blanch" size:50],
                                  };
    self.navigationBar.titleTextAttributes  = attributes;
    CGFloat verticalOffset = -8;
    [[UINavigationBar appearance] setTitleVerticalPositionAdjustment:verticalOffset forBarMetrics:UIBarMetricsDefault];

    UIImage *image = [UIImage imageNamed:NAVBAR_IMAGE];
    [self.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}

This is what it looks like:

在此处输入图片说明

If I comment out the line setting the font this is what it looks like (as expected with the vertical offset):

在此处输入图片说明

The only reason the vertical offset is there is that I thought it might have solved the problem. I don't need it and it is commented out now, but it does NOT change the output - it still looks the same just lower on the NavBar.

Any ideas how to solve this? I think it may be that the custom font has a lot of line-spacing which I guess could be the problem.

I have been trying to find a way to change the origin/height/baseline alignment of the title but can't see a way to do any of these. Any idea how to solve this problem ?

Create a container UIView which is the same width as your label, and height of UINavigationBar (around 46 pixels?). Set clipsToBounds on this container view to YES. Now add your label to this container view, and make the container view the titleView.

Setting Navigationbar image for ios5

if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"YOUR_NAVIGATION_BAR_IMAGE"] forBarMetrics:UIBarMetricsDefault];
}

Setting Navigationbar image for ios6

if([[UINavigationBar appearance] respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"YOUR_NAVIGATION_BAR_IMAGE"] forBarMetrics:UIBarMetricsDefault];

after than create label in center on your navigation bar center with your title.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM