46
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

NavigationBarの戻るボタンをハンドリングしたい

Last updated at Posted at 2018-04-27

※最新(2021年10月)で、進化版の記事はこちら。
https://www.fuwamaki.com/article/154

NavigationBarの戻るボタンって、StoryBoardで作成した際に自動で付いてくれるので非常に便利です。
ただ、戻る時に特定の挙動を加えたい場合、戻る操作イベントをトラッキングしたい場合などは、
戻るボタンをハンドリングする必要があります。

しかし、戻るボタン用のメソッドが用意されていないので、
厳密に戻るボタンをハンドリングすることは難しいです。
ただし、それっぽいことをすることはできます。

参考:navigationbarのバックボタンを押した時に-値を渡したい

開発環境

Mac OS High Sierra 10.13.3
Xcode 9.3
Swift 4

おすすめしたくない方法:viewWillDisappearを利用

viewWillDisappear は、その画面が消えるときに呼ばれる挙動です。
これを用いれば、戻るボタンをハンドリングすることが可能です。
しかし、これだと不便な場合があります。下記例で示します。

【例】
遷移:画面A -> 画面B -> 画面C
目的:画面B -> 画面A に戻る際に確認アラートを出したい
実装:画面Bの viewWillDisappear に確認アラートを表示するコードを記載
-> 問題:画面B -> 画面C でも確認アラートがでてしまう

画面Cが存在しない状況で利用するなら問題ないとは思いますが、おすすめはできません。

おすすめしたい方法:navigationControllerのwillShow

上記の【例】を実現できるコードを下記に記載します。

class BViewController: UIViewController, UINavigationControllerDelegate {

	override func viewDidLoad() {
		super.viewDidLoad()
		navigationController?.delegate = self
	}
	
	func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
	    if viewController is AViewController {
		    //挿入したい処理
	    }
	}
	
}

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) は、その画面(上記だと画面B)から別の画面に遷移したときに呼ばれるメソッドです。

つまり 「B画面からA画面に遷移した時をハンドリング」 しています。
厳密に戻るボタンをハンドリングしているわけではないですが、これなら目的を達成できます。

  • UINavigationControllerDelegate を継承する
  • navigationController?.delegate = self を定義しておく

をお忘れずに。

まとめ

func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) もあったので、便利そうです。

46
39
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
46
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?