原文鏈接:https://www.ioscreator.com/tutorials/change-color-status-bar-tutorial
作者:Arthur Knopper
原文日期:2016/12/29
譯者:Crystal Sun
狀態(tài)欄可以有兩種外觀:dark(黑色) 和 light(白色)。在本章教程中,將學習如何改變狀態(tài)欄的外觀。本節(jié)教程使用的是 Xcode 8.0 和 iOS 10。
打開 Xcode,創(chuàng)建一個 Single View Application。
Product Name 使用 IOS10StatusBarColorTutorial,填寫自己的 Organization Name 和 Organization Identifier,Language 一欄選擇 Swift,Devices 一欄選擇 iPhone。
打開 Storyboard,選中 View,在 Attributes Inspetor 里將 Background Color 改成 Light Gray。運行工程,默認的狀態(tài)欄顏色是黑色(dark)。
而我們想要實現(xiàn)的效果是白色的狀態(tài)欄。打開 ViewController.swift 文件,添加下列代碼:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
上述代碼將 UIStatusBarStyle 枚舉項設為 lightContent。運行工程,這時狀態(tài)欄的顏色變成了白色(light)。
接下來回到 Storyboard,選中 View Controller,在 Editor 菜單中選擇 Embed in Navigation Controller。選中 Navigation Bar,在 Attribute Inspector 里將 Bar Tint color 設置為 red。storyboard 應該如下圖所示。
運行工程,狀態(tài)欄又變成了黑色,也就是默認狀態(tài)。產(chǎn)生這個問題的原因是,iOS 請求的是 navigation controller 的狀態(tài)欄風格,不是 navigation controller 所包含的 controller 的風格。
為了改變 Navigation controller 的風格(style),需要在 AppDelegate.swift 文件里如下修改代碼:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UINavigationBar.appearance().barStyle = .blackOpaque
return true
}
運行工程,這時狀態(tài)欄的顏色變成了白色。
可以從 github 上下載 IOS10StatusBarColorTutorial 教程的源代碼。
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權。