如何在iOS 11与Swift 4中通过AppDelegate编程修改导航栏样式
在iOS 11 & Swift 4中通过AppDelegate全局配置导航栏样式
嘿,我刚好在iOS 11 + Swift 4环境下做过全局导航栏的编程配置,直接在AppDelegate里就能搞定所有页面的统一样式,不用每个ViewController单独设置,分享给你具体实现:
核心实现步骤
所有配置都放在application(_:didFinishLaunchingWithOptions:)方法里,App启动时就会生效:
1. 设置导航栏背景颜色
使用UINavigationBar.appearance()来全局修改导航栏的背景色,对应属性是barTintColor:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 自定义背景色(这里用了一个蓝色示例,你可以换成自己需要的颜色) UINavigationBar.appearance().barTintColor = UIColor(red: 20/255, green: 120/255, blue: 220/255, alpha: 1.0) // 可选:关闭导航栏半透明(如果需要背景色完全不透明显示) UINavigationBar.appearance().isTranslucent = false // 其他配置... return true }
2. 设置导航栏标题的颜色和字体
通过titleTextAttributes属性来配置普通标题的样式,包含颜色和字体:
// 继续在didFinishLaunching方法里添加 let titleStyle: [NSAttributedString.Key: Any] = [ // 标题颜色 .foregroundColor: UIColor.white, // 标题字体:这里用系统半粗体,字号18 .font: UIFont.systemFont(ofSize: 18, weight: .semibold) // 如果要用自定义字体,替换成下面的写法(记得先把字体文件导入项目并配置Info.plist) // .font: UIFont(name: "YourCustomFont-Regular", size: 18)! ] UINavigationBar.appearance().titleTextAttributes = titleStyle
3. (可选)配置iOS 11新增的大标题样式
如果你的App使用了大标题模式,可以同时配置大标题的样式:
// 全局开启大标题(可选,根据你的App设计需求决定) UINavigationBar.appearance().prefersLargeTitles = true let largeTitleStyle: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 34, weight: .bold) ] UINavigationBar.appearance().largeTitleTextAttributes = largeTitleStyle
注意事项
- 自定义字体需要先添加到项目中,并在
Info.plist的Fonts provided by application数组里添加字体文件名(比如YourCustomFont-Regular.ttf)。 - 如果开启了导航栏半透明(
isTranslucent = true),barTintColor会呈现半透明效果,若需要纯色背景,记得关闭半透明。 - 如果某个页面需要特殊的导航栏样式,可以在该ViewController的
viewWillAppear方法里单独覆盖全局配置,比如:
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.barTintColor = .gray }
这样设置后,整个App的导航栏就会统一应用你配置的样式啦,比可视化操作更灵活,适合需要全局统一风格的场景。
内容的提问来源于stack exchange,提问作者mdehghani
相关产品推荐
相关产品推荐

