我希望能够在iOS 11和Swift 4中通过AppDelegate编程地更改导航栏的背景颜色、标题字体和颜色。我知道如何在Xcode中完成这个任务,但是没有找到最新的编程方法。
我希望能够在iOS 11和Swift 4中通过AppDelegate编程地更改导航栏的背景颜色、标题字体和颜色。我知道如何在Xcode中完成这个任务,但是没有找到最新的编程方法。
For changing the Navigation bar's background color
self.navigationController?.navigationBar.barTintColor = UIColor.white
For changing Navigation bar's title and Bar button colors
self.navigationController?.navigationBar.tintColor = UIColor.black
For changing font
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()。我正在使用相同的代码,并且它能很好地工作。
对于AppDelegate:
将以下代码放入AppDelegate
的didFinishLaunchingWithOptions
中:
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]
。 - Klemens Zleptnig只需使用UINavigationBar.appearance()
例如:
UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.white]
或者
UINavigationBar.appearance().barTintColor = .blue
iOS 15现在已经可以
navigationController.navigationBar.backgroundColor = .white