【发布时间】:2018-05-04 07:15:57
【问题描述】:
我想通过 AppDelegate 在 iOS 11 和 swift 4 中以编程方式更改导航栏背景颜色、标题字体和颜色。我知道如何使用 Xcode 执行此操作,但没有找到以编程方式执行此操作的最新解决方案。
【问题讨论】:
标签: ios swift swift4 ios11 appdelegate
我想通过 AppDelegate 在 iOS 11 和 swift 4 中以编程方式更改导航栏背景颜色、标题字体和颜色。我知道如何使用 Xcode 执行此操作,但没有找到以编程方式执行此操作的最新解决方案。
【问题讨论】:
标签: ios swift swift4 ios11 appdelegate
以下是仅针对特定 ViewController 执行此操作的步骤。
我创建了一个 BaseViewController 文件,它是我所有 ViewController 的父级。 BaseViewController 的 viewDidLoad() 中添加了以下代码。
用于更改导航栏的背景颜色
self.navigationController?.navigationBar.barTintColor = UIColor.white
用于更改导航栏的标题和栏按钮颜色
self.navigationController?.navigationBar.tintColor = UIColor.black
换字体
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red, NSAttributedStringKey.font : UIFont.sourceSansPro(ofSize: 18.0), NSAttributedStringKey.kern:1.5]
【讨论】:
您可以使用以下代码更改背景颜色和标题字体。
func setupNavigationBarAppearance() {
UINavigationBar.appearance().tintColor = .black
UINavigationBar.appearance().shadowImage = UIImage.imageFromColor(.black, width: 1.0, height: 1.0)?.resizableImage(withCapInsets: .zero, resizingMode: .tile)
UINavigationBar.appearance().isTranslucent = false
let font:UIFont = UIFont(name: "ProximaNova-Bold", size: 18.0)!
let navbarTitleAtt = [
NSAttributedStringKey.font:font,
NSAttributedStringKey.foregroundColor: UIColor.white
]
UINavigationBar.appearance().titleTextAttributes = navbarTitleAtt
}
并在 didFinishLaunchingWithOptions 中将此函数称为 setupNavigationBarAppearance()。我正在使用相同的代码,并且工作正常。
【讨论】:
只需使用UINavigationBar.appearance()
例如:
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
或
UINavigationBar.appearance().barTintColor = .blue
【讨论】:
对于AppDelegate:
将以下代码放入didFinishLaunchingWithOptionsAppDelegate:
UINavigationBar.appearance().barTintColor = UIColor(red: 46.0/255.0, green: 14.0/255.0, blue: 74.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
UINavigationBar.appearance().isTranslucent = false
【讨论】:
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
现在在 iOS 15 上
navigationController.navigationBar.backgroundColor = .white
【讨论】: