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
}