使って創ってApp

ソフトウェアを使ったり作ったりするブログです

プログラムからStoryboardの画面遷移を実行する

プログラムからStoryboardの画面遷移を実行します。遷移先と遷移元を往来できるようになります。performSegueWithIdentifier dismissViewControllerAnimated メソッドで画面を遷移させます。

開発環境

完成予定図

f:id:hitxutokun:20151217230341g:plain

Segue を設定

ViewControllerを追加してSegueを追加します。

では作ってみましょう。新規プロジェクトを作成します。テンプレートは Single View Application を選択し、プロジェクト名は Demo_Segueにしました。

  1. Main.storyboard を開いて、ViewController を Object Library から追加します。違いが分かりやすいように背景色を変えました

  2. 新規に Cocoa Touch ファイルを作成します。SubclassをUIViewControllerにして、ファイル名を NewViewController にしました。

    f:id:hitxutokun:20151217232845p:plain

  3. Main.storyboardに移動して、追加した方の ViewController の Custom Class を、NewViewController に設定します。

    f:id:hitxutokun:20151217234314p:plain

  4. Document Outline 画面で、ViewControllerを右クリックしたまま NewViewController までドラッグして離し、Segue の 種類を Show に設定します

    f:id:hitxutokun:20151217234922g:plain

  5. 追加された Segue を Document Outline 画面で選択し、Attribute Inspecter 画面で Identifier を NewViewController に設定します

    f:id:hitxutokun:20151217235401p:plain

画面遷移のプログラムを書く

performSegueWithIdentifier dismissViewControllerAnimated メソッドで画面を遷移させます。

  1. それぞれの ViewController の View に Button を一つずつ配置し、Action を それぞれの ViewController に以下のように関連付けます

    クラス名 メソッド
    ViewController showNextViewController
    NewViewController showViewController
  2. メソッド内に画面遷移のプログラムを書きます
    // ViewController.swift
    @IBAction func showNextView(sender: AnyObject) {
      self.performSegueWithIdentifier("NextViewSegue", sender: nil)
    }
    // NewViewController.swift
    @IBAction func showViewController(sender: AnyObject) {
      self.dismissViewControllerAnimated(true, completion: nil)
    }

これで完成です!実行してボタンを押してください。画面が遷移しましたか?

まとめ

画面をプログラムで遷移させるには2つのメソッドを使う

  • performSegueWithIdentifier: 指定した Identifier の Segue を実行する
  • dismissViewControllerAnimated: ViewController をメモリから削除する。その際、アニメーションを実行する