view.backgroudColorに色を指定する
self.view.backgroudColor = .white
画面そのもののviewに背景色を指定してあげると、ステータスバーの背景色を変更できます。
問題点としてはview全体の色を変更してしまうのでステータスバーだけの色を変更したい場合には使えない点です。
ステータスバー部分に背景色変更用のUIViewを追加する
extension UIViewController {
private final class StatusBarView: UIView { }
func setStatusBarBackgroundColor(_ color: UIColor?) {
for subView in self.view.subviews where subView is StatusBarView {
subView.removeFromSuperview()
}
guard let color = color else {
return
}
let statusBarView = StatusBarView()
statusBarView.backgroundColor = color
self.view.addSubview(statusBarView)
statusBarView.translatesAutoresizingMaskIntoConstraints = false
statusBarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
statusBarView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
statusBarView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
statusBarView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
}
}
コメント