LoginSignup
207
200

More than 5 years have passed since last update.

SwiftでAppDelegateを使った画面間のデータ受け渡し

Posted at

画面間でデータを受け渡す方法はいくつかあると思いますが、一番シンプルな方法はきっとAppDelegateを使う方法なんじゃないかな。

今回は、受け渡したい側のViewControllerをsendViewController、受け取りたい側のViewControllerをrecieveViewControllerとします。

まずは、AppDelegateに受け渡す変数を用意しておく。なんでもいいけど、今回はString型にします。

AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
    var message:String?
.
.
.
(略)

次にsendViewControllerの適当なメソッド内で先ほどの変数に渡したい値を代入する

sendViewController
    var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate //AppDelegateのインスタンスを取得 
    appDelegate.message = "message" //appDelegateの変数を操作

最後にrecieveViewControllerでAppDelegateから変数の値を受け取る

recieveViewController
   var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate //AppDelegateのインスタンスを取得 
   var message = appDelegate.message

これで、辞書型でもなんでも、データの受け渡しが可能になると思います。

207
200
3

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
207
200