SwiftのUIViewController間でデータを受け渡す話
おはようございます、かびさん@あおかびんです。
iPhoneアプリをSwiftを使って開発しているのですが
UIViewController間でデータを渡したいときに
AppDelegate.swiftに変数を追加すると渡せるということだったので
その方法を記述したいと思います。
1.AppDelegate.swift
AppDelegate.swiftファイルの中に、値を保持する領域を宣言します。
具体的には、
class AppDelegate: UIResponder, UIApplicationDelegate { var message: String? ・・・ }
こんな感じですかね。
2.SendViewController.swif (受け渡しView)
値に書き込むためにはAppDelegateクラスの変数を用意して、
その変数のクラス変数(?)を経由して書き込む形になります。
class SendViewController: UIViewController { var delegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate ・・・ // ボタンを押したときの処理 func touchButton(sender: UIButton){ // AppDelegateのmessageに押されたボタンのtagを代入 self.delegate.message = String(sender.tag) // NavigationControllerを使ったページの遷移 let receiveViewController: ReceiveViewController = ReceiveViewController() self.navigationController?.pushViewController(receiveViewController, animated: true) } }
こんな感じで記述しました。
(今回NavigationControllerを使っているので、ちょっとややこしいかもしれない)
3.ReceiveViewController.swift (値の受け取りView)
class ReceiveViewController: UIViewController { var delegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate override func viewDidLoad() { super.viewDidLoad() println(self.delegate.message) } ・・・ }
2と同じように呼び出しを行って、値を吐き出しています。
多分うまくいくんじゃないかな
ダメだったら連絡ください、修正します。。。
これを知らなかったからViewのinitをoverrideしようと苦戦してた。。。
スキル無さすぎダメダメのダメ。
すみません、以上あおかびんでした。