LoginSignup
17
16

More than 5 years have passed since last update.

[Swift4] NavigationBarのBackボタンを、遷移先別にカスタムする方法

Last updated at Posted at 2018-06-05

状況

ViewController(以降VC)間の遷移において、NavigationBarの戻るボタン画面ごとにカスタムしたい

こうやる

こんな場面を例に

  • VC_A → VC_B の時は、戻るボタンのテキストを"hoge_AtoB"にしたい。
  • VC_A → VC_C の時は、戻るボタンのテキストを"fuga_AtoC"にしたい。
  • また、VC_A → VC_C の時は、戻る時に処理を行ったり、遷移をキャンセルしたりもしたい。

実装

class VC_A: UIViewController, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.delegate = self
    }

  func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        if viewController is VC_B {
            navigationItem.backBarButtonItem = UIBarButtonItem(
                title: "hoge_AtoB", 
                style: .plain, 
                target: nil, 
                action: nil)
        }
        if viewController is VC_C {
            navigationItem.backBarButtonItem = UIBarButtonItem(
                title: "fuga_AtoC", 
                style: .plain, 
                target: nil, 
                action: #selector(VC_A.backAction(sender :)))
        }
    }

    @objc func backAction(sender: UIBarButtonItem)  {
        // ここで色々処理できる

        self.navigationController?.popViewController(animated: true)
    }

}

ポイント

  • 遷移元で、Backボタンを定義する
  • NavigationControllerのdelegateメソッドを利用し、navigationのタイミングで、遷移先別に処理を行う
17
16
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
17
16