LoginSignup
2
4

More than 5 years have passed since last update.

[iOS] ステータスバーの表示/非表示に対応する

Posted at

背景

通常のiOSアプリ開発であればステータスバーの表示/非表示を自分自身で管理できるため、UIの実装にそれほど気を使う必要はありません。ただしiOSアプリ向けのSDKを開発する場合で、かつフルスクリーンで表示する何らかのViewまたはViewControllerを実装しているなら、クライアントアプリ側のステータスバーの表示/非表示の両方の場合に対応する必要があるでしょう。本記事ではアプリ側に何らかのView(ViewController)をフルスクリーンで表示するSDKを開発する場合を想定し、ステータスバーの表示設定に応じてUIを調整する手法を紹介します。

Constraintの設定

例えばSDK側で実装するViewControllerがNavigationBarを持っている場合、NavigationBarとSuper View(親View)の間にTop Constraintを指定し、propertyとしてコードに登録しておきます。

@IBOutlet weak var navigationBarTopConstraint: NSLayoutConstraint!

frameとconstraintを調整するメソッドを用意

クライアントアプリ側のステータスバーの表示/非表示はViewControllerのprefersStatusBarHiddenか、UIApplication.shared.isStatusBarHiddenで判定できるため、それらの値に応じてConstraintの値とViewのframeを調整するメソッドを用意します。

viewのframeとconstraintを調整する
func adjsut(view: UIView, constraint: NSLayoutConstraint) {
    let statusBarHeight: CGFloat = 20
    let margin: CGFloat = (self.prefersStatusBarHidden || UIApplication.shared.isStatusBarHidden) ? 0 : statusBarHeight

    constraint.constant = margin
    view.frame = CGRect(x: view.frame.origin.x,
                        y: margin,
                        width: view.frame.size.width,
                        height: view.frame.size.height)
}

使用方法

UIViewControllerのviewDidLayoutSubviewsで上記のメソッドを呼ぶことで、クライアントアプリ側の設定に応じてViewのframeとConstraintを調整することができます。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.adjsut(view: self.navigationBar, constraint: self.navigationBarTopConstraint)
}
2
4
0

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
2
4