要改變 status bar 上的文字/icon 顏色 (白色或黑色),一行就可以:
UIApplication.shared.statusBarStyle = .default //或 .lightContent
但在 xcode 10 後會出現警告
Setter for 'statusBarStyle' was deprecated in iOS 9.0: Use -[UIViewController preferredStatusBarStyle]
雖然有警告,實際在 iOS 12 上卻能正常執行也有效果出來
不過合格的寫法應該是
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } var setStatusBarDark = true { didSet { self.setNeedsStatusBarAppearanceUpdate() } } override var preferredStatusBarStyle: UIStatusBarStyle { return setStatusBarDark ? .default : .lightContent } @IBAction func btnDefault(_ sender: Any) { setStatusBarDark = true } @IBAction func btnLight(_ sender: Any) { setStatusBarDark = false } }
但若畫面有 Navagation Controller 時,必須 extension UINavigationController 後才有作用
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
var setStatusBarDark = true {
didSet {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return setStatusBarDark ? .default : .lightContent
}
@IBAction func btnDefault(_ sender: Any) {
setStatusBarDark = true
}
@IBAction func btnLight(_ sender: Any) {
setStatusBarDark = false
}
}
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? .default
}
}
參考
How to set Status Bar Style in Swift 3
iOS 设置了preferredStatusBarStyle不起作用,原来是这样啊
导航栏的平滑显示和隐藏 - 个人页的自我修养(1)
Swift 修改状态栏
Status bar throwing tantrums in iOS 9+