首页 文章

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

提问于
浏览
16

我想将 Headers 的字体改为Avenir,我想把它变成白色 . 这是我在 viewDidLoad 方法中的代码:

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

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

这是我的UINavigationBar的样子:
enter image description here

我希望 Headers 也有Avenir的字体 . 我该如何实现这一目标?

5 回答

  • 5

    我用这个:

    更新,似乎也需要这样:

    self.navigationController?.navigationBar.barStyle       = UIBarStyle.Black // I then set the color using:
    
        self.navigationController?.navigationBar.barTintColor   = UIColor(red: 204/255, green: 47/255, blue: 40/255, alpha: 1.0) // a lovely red
    
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() // for titles, buttons, etc.
    
        let navigationTitleFont = UIFont(name: "Avenir", size: 20)!
    
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: navigationTitleFont]
    
  • 24

    如果您希望在整个应用程序中应用样式,请在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 为 Headers 文本设置自定义字体 .

    NSShadowAttributeName 对文本应用了漂亮的阴影效果,如果需要,可以删除此部分 .

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

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

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

  • 1

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

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

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

    @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)!]
    }
    
  • 0

    如果有人在 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)!]
    

相关问题