LoginSignup
10
6

More than 5 years have passed since last update.

[swift3] 特定の画面でStatusBarを隠す方法

Last updated at Posted at 2017-07-25

iOS7以降から有効になったprefersStatusBarHiddenを使う。

Info.plist

View controller-based status bar appearanceキーを追加してYESを設定。

prefersStatusBarHidden

StatusBarを隠したいViewControllerで以下を実装。

override var prefersStatusBarHidden: Bool {
    return true
}

問題点 1

StatusBarStyleが死ぬ

StatusBarを白くしたいので設定していた以下の内容が無効になる。

  • Info.plistのStatus bar styleUIStatusBarStyleLightContent
  • AppDelegateで実装していたapplication.statusBarStyle = .lightContent

解決策

ViewControllerに以下を実装したら解決した。

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

問題点 2

LandscapeでStatusBarが消えない

今までLnadscapeModeになると自動的にStatusBarが非表示になっていたのに表示されてしまう。
-> View controller-based status bar appearanceYESに設定したせいだと思う。

解決策

LandscapeとPortrateに突入する際にprefersStatusBarHiddenがコールされるので、そこで適切な値を返してあげればよい。
例としては以下。

class ViewController: UIViewController {

    var isStatusBarHidden = false

    override var prefersStatusBarHidden: Bool {
        return isStatusBarHidden
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        NotificationCenter.default.addObserver(self, selector: #selector(didRotateScreen), name: .UIApplicationDidChangeStatusBarOrientation, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func tapButton(_ sender: UIButton) {
        isStatusBarHidden = !isStatusBarHidden
        setNeedsStatusBarAppearanceUpdate()
    }

    func didRotateScreen() {
        if UIDevice.current.orientation.isLandscape {
            isStatusBarHidden = true
        } else if UIDevice.current.orientation.isPortrait {
            isStatusBarHidden = false
        }
    }
}

余談

上記のコードで記述している@IBAction func tapButtonは、storyboardに配置した"StatusBarの表示/非表示を切り替えるボタン"に接続するIBActionです。
メソッド内で実行しているsetNeedsStatusBarAppearanceUpdate()は、実行した時点でStatusBarの表示を更新してくれます。(すなわちprefersStatusBarHiddenが実行される)

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