使用Swift从AppDelegate更改UINavigationBar后退按钮文本和字体

我需要从AppDelegate更改UINavigationBar后退栏按钮文本,以将更改应用到我的应用程序中的所有Views

我使用以下方法更改了标题字体样式:

 UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName: UIFont(name: "MyCustomFont", size: 20)! ] 

但我不知道如何访问左侧栏按钮对其进行更改。

斯威夫特3.0,4.0

只需通过UINavigationItem extension即可实现。 根据许多搜索,无法使用app delegate更改左按钮文本。

 extension UINavigationItem{ override open func awakeFromNib() { super.awakeFromNib() let backItem = UIBarButtonItem() backItem.title = "Hello" if let font = UIFont(name: "Copperplate-Light", size: 32){ backItem.setTitleTextAttributes([NSFontAttributeName:font], for: .normal) }else{ print("Font Not available") } /*Changing color*/ backItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.green], for: .normal) self.backBarButtonItem = backItem } } 

更新:

您可以在didFinishLaunchingWithOptions上更改AppDelegate后退按钮箭头颜色,

  /*It will change back arrow color only if you use backItem.setTitleTextAttributes, else it will change whole text color*/ UINavigationBar.appearance().tintColor = UIColor.orange 

尝试这个:

  1. UINavigationController子类化并使用它。 然后像这样制作你的viewDidLoad :(根据你的需要改变属性)

     // // NavConViewController.swift // customattributedbackbtn // // Created by Glenn Posadas on 8/12/17. // Copyright © 2017 Glenn Posadas. All rights reserved. // import UIKit class NavConViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let font = UIFont(name: "Helvetica-Light", size: 12)! var attributes: [String : Any] = [NSFontAttributeName : font] attributes[NSForegroundColorAttributeName] = UIColor.black UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self, NavConViewController.self]).setTitleTextAttributes(attributes, for: .normal) } } 

样本输出:

默认

在此处输入图像描述

归因

在此处输入图像描述

这应该对你有帮助

 UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "MyCustomFont", size: 20)!], for: .normal) 

要更改图像颜色,您可以使用字体文件并更改颜色,也可以使用所需颜色的图像。

 let yourBackButtonIcon = //YourImage here let navigationBar = UINavigationBar.appearance() navigationBar.backIndicatorImage = yourBackButtonIcon navigationBar.backIndicatorTransitionMaskImage = yourBackButtonIcon 

要更改后退按钮标题文本颜色

 navigationBar.titleTextAttributes = [NSFontAttributeName: yourFont, NSForegroundColorAttributeName: yourColor] 

注意:-

上面的代码应该在applicationDidFinishLaunching方法的AppDelegate类中