0
0

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.

segueを使って前の画面へ遷移する

Posted at

はじめに

segueを使って画面遷移をしているときに、画面を戻したい場面があったのですが、
実装するのに時間がかかりました。
今回の記事では、segueを使って画面を前に戻す方法を紹介します。

ソースコードです!
https://github.com/h-taro/WithSegue

環境

Xcode 12.5.1
Swift 5.4.2
macOS Big Sur 11.5.2

前提条件

動画のようにfirst, second, thirdというように画面を表示するアプリケーションがあります。

今回はthird画面からfirst画面へ戻りたいです。

実装方法

大まかな実装方法は次です!

  1. 遷移先の画面にUIStoryBoardSegueを引数に持つ関数を定義する
  2. 遷移元の画面にUnwind segueを定義する
  3. 定義したUnwind seguesegue identifierを定義する
  4. 任意のタイミングでperformSegue(withIdentifier: "")を実行する

Unwind segueの設定方法

まず、遷移先の画面(今回はFirstViewController)にUIStoryboardSegueを引数に持つ関数を定義します。

FirstViewController.swift
@IBAction func showFirst(segue: UIStoryboardSegue) {
}

次は遷移元画面(今回はThirdViewController)での作業です。
Third画面ボタンからExitへドラッグ&ドロップすることで
Unwind Segueを定義しました。
定義したUnwind SegueshowFirstというSegue Identifierを設定しています。

ボタンタップ時に画面遷移する

最後にボタンタップ時にperformSegueを実行します!
withSegueIdentiferには前の手順で設定したSegue Identifierを使います。

ThirdViewController.swift
@IBAction func tapCautionButton(_ sender: UIButton) {
    performSegue(withIdentifier: "showCaution", sender: nil)
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?