2
4

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.

【Swift】簡単な画面遷移まとめ

Posted at

パターン

  • ボタンを押したら画面遷移
  • 条件で画面遷移
  • 変数を渡して画面遷移

追加するかも。

ボタンを押したら画面遷移

  1. 『NEXT』とか『次へ』みたいなボタンを設置する。
  2. ボタンを controlキー を押しながらクリックして遷移したい画面にドラッグドロップ

スクリーンショット 2020-12-05 19.11.08.png

  1. そしたらオプションが出てくるので選択する

スクリーンショット 2020-12-05 19.18.59.png

条件で画面遷移

  1. 上部のアイコンを controlキー を押しながらクリックして遷移したい画面にドラッグドロップ

スクリーンショット 2020-12-05 19.21.19.png

  1. 上記の『3』と同じくオプションが出てくるので選択する

スクリーンショット 2020-12-05 19.21.26.png

  1. 画面遷移の矢印("Segue" セグエという)をクリックしてIdentifierで名前(というかID)をつける

7fddf47749010b61ea2655b2e425fe18.png

  1. if の中でコードを書く
ViewController.swift
    if 条件式 {
      // 『3』で設定したIDを書く
      performSegue(withIdentifier: "next", sender: nil)
    }

変数を渡して画面遷移

  1. prepare のメソッドを書いて値を渡す準備をする

prepare と書いて出てきたものを選択すると自動補完してくれる。

スクリーンショット 2020-12-05 20.05.51.png

渡す

ViewController.swift

  // 渡したい変数
  var face = "(´・ω・`)"

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    // 遷移先のコントローラ名を書く。ここではNextViewController
    let nextVC = segue.destination as! NextViewController
    
    // 受け取る先で定義する変数名(後述)に渡したい変数を代入する  
    nextVC.nextFace = face
  }

受け取る

 NextViewController.swift

  // 例えばLabelを設置しておいてそこで受け取る
  @IBOutlet weak var nextLabel: UILabel!
  var nextFace = ""

  override func viewDidLoad() {
        super.viewDidLoad()

      nextLabel.text = nextFace
    }

遷移先のLabelに (´・ω・`) が表示される。
実用的なところでは計算した答えとか遷移先に渡すとかがいいと思う。

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?