LoginSignup
13
16

More than 5 years have passed since last update.

Swift3でステータスバーエリアの色を変える

Posted at

Swift3でステータスバーエリアの20pxの背景色を変えたい場合のTipsです。

Xcode7.3、Swift2環境からそのままSwift3にConvertして以下のようなコードにすると実行時にクラッシュします。

'NSUnknownKeyException', reason: '[<_SwiftValue 0x60800049a9a0> valueForUndefinedKey:]: 

となります。

    func setStatusBarBackgroundColor(color: UIColor) {
        guard let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as AnyObject).value(forKey: "statusBar") as? UIView else {
            return
        }
        statusBar.backgroundColor = color
    }

なので以下のように変えてあげると綺麗にXcode7.3などでビルドしたのと同じような状態になります。

    func setStatusBarBackgroundColor(color: UIColor) {
        guard let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIView else {
            return
        }
        let statusBar = statusBarWindow.subviews[0] as UIView
        statusBar.backgroundColor = color
    }
13
16
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16