LoginSignup
15
10

More than 3 years have passed since last update.

iOSでステータスバーの背景色を変える拡張関数(Swift)

Last updated at Posted at 2020-06-23

はじめに

iOSでは、ステータスバーの背景色を単体でかんたんに変えることができません。
UIViewController#view.backgroundColor を指定するとステータスバーの背景色が変わりますが、同時にビュー全体の背景色も変わってしまいます。

いくつか方法はあるのですが、今回は「上左右をSuperviewに合わせ、下をSafe Areaの上に付けたビュー」を追加することで実現します。
Storyboardを作成するたびに手動でビューを追加するのは手間なので、呼び出すだけでステータスバーの背景色を変えられる拡張関数を実装しました。

環境

  • OS:macOS Mojave 10.14.6
  • Xcode:11.3.1 (11C504)
  • Swift:5.1.3
  • iOS:13.3

実装

UIViewController に拡張関数を追加します。

UIViewController+StatusBar.swift
import UIKit

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
    }
}

複数回呼ばれてもビューが重ならないよう、処理の最初で StatusBarView があったら剥がすようにしています。

使い方

UIViewControllerviewDidLoad() で色を指定して呼び出すのみです。

FooViewController.swift
final class FooViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        configureView()
    }

    private func configureView() {
        setStatusBarBackgroundColor(.blue)
    }
}

ノッチの有無にかかわらず、ステータスバーの背景色が変わります。

iPhone 8 iPhone 11 Pro Max
Simulator Screen Shot - iPhone 8 - 2020-06-23 at 15.17.25.png Simulator Screen Shot - iPhone 11 Pro Max - 2020-06-23 at 15.27.39.png

参考リンク

15
10
2

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
15
10