LoginSignup
5
3

More than 3 years have passed since last update.

[Swift 5]画面を縦スクロールした時にNavigationBarを隠したり出したり(UIScrollViewDelegate)

Last updated at Posted at 2019-08-22

縦スクロールされたとき、NavigationBarをスッと隠すアニメーション、かっこいいですよね。
コンテンツ表示を広くとれるのでユーザーにとっても嬉しい挙動だと思います。

UITableView等のUIScrollViewを親に持っているViewを使っている場合は以下のように書くだけで簡単に作用します。

delegateは設定してあると思いますが、確認しておきましょう。※詳しくは後述

ViewController.swift
final class ViewController: UIViewController {

    // スクロールでNavigationBarを隠す
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let isBarHidden = scrollView.panGestureRecognizer.translation(in: scrollView).y < 0
        navigationController?.setNavigationBarHidden(isBarHidden, animated: true)
    }
}

ただし、ScrollViewを使用していない、UIStackViewやUILabel、UIButtonなどだけで構成された画面の場合はもう一手間必要です。

UIScrollViewDelegateに適合する必要がありますので、以下のように書きましょう。

ViewController.swift
final class ViewController: UIViewController {
    // 省略
}

extension ViewController: UIScrollViewDelegate {
    // スクロールでNavigationBarを隠す
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let isBarHidden = scrollView.panGestureRecognizer.translation(in: scrollView).y < 0
        navigationController?.setNavigationBarHidden(isBarHidden, animated: true)
    }
}

追記:delegateの追加の必要な場合もある

例えば、単一のUITextViewで構成されたViewControllerの場合は、delegateを繋いでおく必要がありますのでご注意を。
StoryboardでUITextViewからViewControllerへcontrolボタンを押しながらドラッグし、Outletsdelegateを選べばOKです。
スクリーンショット 2019-08-23 14.12.18.png

以上です。

参考

5
3
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
5
3