导航栏标题对齐中心

时间:2013-08-23 23:54:22

标签: objective-c

AppDelegate.m Navbar Customization:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar"] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setTitleTextAttributes: @{
                            UITextAttributeTextColor: [UIColor colorWithRed:(56/255.0) green:(61/255.0) blue:(63/255.0) alpha:1],
                            UITextAttributeTextShadowColor: [UIColor grayColor],
                            UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                            UITextAttributeFont: [UIFont fontWithName:@"ProximaNova-Bold" size:15.0f]
 }];

LViewController.m Navbar自定义左/右按钮:

// Left Button
UIButton *leftButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[leftButton setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
[leftButton addTarget:self action:@selector(openLeftMenu) forControlEvents:UIControlEventTouchUpInside];
[leftButton setFrame:CGRectMake(0, 0, 45, 44)];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];

// Right Button
UIButton *rightButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[rightButton setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
[rightButton addTarget:self action:@selector(openRightMenu) forControlEvents:UIControlEventTouchUpInside];
[rightButton setFrame:CGRectMake(0, 0, 45, 44)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

结果(标题不居中):

Title not Centered

我尝试了很多提示,但是有人工作了:

1 个答案:

答案 0 :(得分:0)

在文本的垂直方向上,在iOS上使用自定义字体充满了危险。这里最好的选择是将标题嵌入UILabel,然后将UILabel放在UIView中,并进行适当的定位。像这样:

UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.text = @"Test";

UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0.0f,
                                                             0.0f,
                                                             320.0f,
                                                             44.0f)];

titleLabel.frame = …; // Compute the frame you need based on the chosen font, set
                      // appropriately.

[container addSubview:titleLabel];

self.navigationItem.titleView = container;