LoginSignup
12
10

More than 5 years have passed since last update.

Swift で関数から View 遷移と、AppDelegateで画面間の値渡し

Last updated at Posted at 2015-09-25

遷移元のコントローラで、何か処理してから遷移する。

#他のサイト拝見しながら、どうにもうまくいかない部分もあったので。
#バージョン変わったりいろいろアップデートがねー。
#Xcode version : 6.4 -> 7.0 アップデートの修正を反映

例えば Main.storyboad 内のViewで、遷移先のViewのIdentity>StoryboadIDを「mySecondView」と定義している場合、
遷移元のコントローラの遷移するコードはこんな感じになる。

func hogehoge(){
        // なにか処理。例えばラベルの値を変える
        label.text = "sample" //labelはあらかじめ@IBOutletで定義しておく

        //遷移するViewを定義する
        //下記は6.4のときのコード
        //let mySecondView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("mySecondView") as! UIViewController
        //こっちが7.0
        let mySecondView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("mySecondView")

        //アニメーションを設定する
        mySecondView.modalTransitionStyle = UIModalTransitionStyle.PartialCurl

        //Viewの移動をする
        self.presentViewController(mySecondView, animated: true, completion: nil)
}

値の受け渡し
AppDelegate.swiftで

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
   var viewVal: String?
   //以下略
}

遷移元で値セット

override func viewWillDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.viewVal = label.text!
    }

遷移先で受け取り

    override func viewWillAppear(animated: Bool) {
        super.viewDidDisappear(animated)
        var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        label.text = appDelegate.viewVal
    }

12
10
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
12
10