如何在UINavigationBar中设置自定义字体?

6
我该怎样在UINavigationBar中设置自定义字体?我需要Tahoma字体。
- (void)viewDidLoad{
    self.title =@"My text";
}

alt text


1
Tahoma字体是由微软公司拥有的。一旦您解决了许可问题,请告诉我们,我们将帮助您进行编码。 :-) - John Parker
但是iPhone已经内置了Tahoma字体,我不需要任何许可证。 - Voloda2
2
Tahoma 不是内置字体之一。 - grahamparks
grahamparks,我上传了图片。 - Voloda2
10
这是你的 Mac 上安装的字体列表,而不是可用于 iOS 设备的字体。 - Brad Larson
2个回答

21

完全可以做到,但可能需要费些功夫。一旦您找到所需的字体(可以是iOS已经提供的替代字体之一,也可以是您拥有正确许可证的TTF文件),只需创建一个UILabel,并设置其大小、格式、字体等,然后将其添加到该栏的导航项中(或者,如果您在视图控制器中进行操作,则将该控制器的.navigationItem.titleView设置为您的标签)。

例如,我有一个位于UINavigationController内部的视图控制器。要将顶部的标签更改为自定义字体,我只需执行以下操作:

//...I have already setup a UILabel called navLabel that has the same style as a 
// default navigation bar title, but I've changed the .font property to my custom font
self.navigationItem.titleView = navLabel;
[navLabel release];

请提供可用字体列表,例如此处 - Mihai Timar

17

这段代码应该能够正常运行。在呈现您的主要 UI 的 UIViewController 中:

- (void)viewDidLoad
{
        [super viewDidLoad];

        int height = navigationController.navigationBar.frame.size.height;
        int width = navigationController.navigationBar.frame.size.width;

        UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        navLabel.backgroundColor = [UIColor clearColor];
        navLabel.textColor = [UIColor whiteColor];
        navLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        navLabel.font = [UIFont boldSystemFontOfSize:15];
        navLabel.textAlignment = UITextAlignmentCenter;
        self.navigationItem.titleView = navLabel;
        [navLabel release];
}
请注意,生成的自定义视图具有透明背景,因此您可以使用[navigationController.navigationBar addSubview:view]向导航栏添加更多内容。这可以是工具栏左上角的旋转指示器或其他东西。
如果您使用自定义视图,则将无法再使用uiviewcontroller标题设置标题。您需要使用您的自定义视图提供的可用方式来设置标题。
例如:
((UILabel *)self.navigationItem.titleView).text = title;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接