如何更改UINavigationBar标题的字体和文本颜色

时间:2015-08-06 03:20:49

标签: ios swift fonts uinavigationcontroller uinavigationbar

我想将标题的字体更改为Avenir,我想将其设为白色。这是我在viewDidLoad方法中的代码:

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir", size: 20)!]
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]

此代码仅更改标题的颜色,而不是字体。另外,我尝试在App Delegate File中实现它,但这不起作用。

以下是我的UINavigationBar的样子:enter image description here

我希望标题也有Avenir的字体。我如何实现这一目标?

6 个答案:

答案 0 :(得分:31)

我用这个:

更新,似乎还需要这样做:

,

答案 1 :(得分:10)

如果您希望在整个应用程序中应用样式,请在AppDelegate.m文件中添加这些行。

NSShadow* shadow = [NSShadow new]; 
shadow.shadowOffset = CGSizeMake(0.0f, 0.0f); 
shadow.shadowColor = [UIColor blackColor]; 

[[UINavigationBar appearance] setTitleTextAttributes: @{
NSForegroundColorAttributeName: [UIColor whiteColor],
NSFontAttributeName: [UIFont fontWithName:@"Kelvetica Nobis" size:20.0f],
NSShadowAttributeName: shadow 
}];

NSForegroundColorAttributeName 设置字体颜色。

NSFontAttributeName 为标题文字设置自定义字体。

NSShadowAttributeName 会对文字应用漂亮的阴影效果,如果需要,可以删除此部分。

此外,您可以添加这些行,以便在导航到导航控制器中的另一个视图时隐藏操作栏中后退按钮中显示的文本。

[[UIBarButtonItem appearance]
     setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
     forBarMetrics:UIBarMetricsDefault];

希望这有助于你的问题:)

答案 2 :(得分:5)

您的代码没问题,只需将titleTextAttributes设置为一行:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white , NSFontAttributeName: UIFont(name: "Avenir", size: 17)!]

答案 3 :(得分:3)

万一有人在 Swift 4 中使用它:

let navBarAppearance = UINavigationBar.appearance()
navBarAppearance.barTintColor = .red
navBarAppearance.tintColor = .white
navBarAppearance.titleTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.white,
        NSAttributedString.Key.font: UIFont(name: "Avenir", size: 20)!]

答案 4 :(得分:1)

我只想创建一个插座并执行此操作:

@IBOutlet weak var navigationBar: UINavigationBar!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir", size: 30)!]
}

答案 5 :(得分:1)

Swift 5 中:

let appearance = UINavigationBarAppearance()
    appearance.titleTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.white,
        NSAttributedString.Key.font: UIFont(name: "Avenir", size: 20)!]
    appearance.largeTitleTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.white,
        NSAttributedString.Key.font: UIFont(name: "Avenir", size: 35)!]

此处的代码用于标题和大标题。如果需要系统字体,也可以删除自定义字体。

相关问题