2017-05-17 2 views
1

私は、モーダルに提示されたotherVC内のあるrootVCからの情報を使用したいと思います。ここでの設定は次のとおりです。rootVCとモーダルに提示されたotherVCとの間で情報を転送できませんか?

protocol OtherVCDelegate { 
    func didHitOK() 
    func didHitCancel() 
} 


class ViewController: UIViewController, OtherVCDelegate { 
    func didHitCancel() { 
     //do a function 
    } 

    func didHitOK() { 
     //do another function 
    } 
    var stringy = "Hello" 

    @IBAction func ButtonAction(_ sender: Any) { 

     let otherVC = self.storyboard?.instantiateViewController(withIdentifier: "AlertVC") as! AlertVC 
     otherVC.modalPresentationStyle = .overCurrentContext 
     otherVC.delegate = self 
     otherVC.label.text = stringy //THIS is where my question focuses 
     self.present(otherVC, animated: true, completion: nil)//presents the other VC modally 

    } 

otherVCは、「ラベル」という名前のUILabelを持っています。しかし、ButtonAction関数を実行すると、オプションの値をアンラップするときに予期せずnilが見つかったため、xcodeが致命的なエラーを検出するという問題がありました。 ButtonActionの中にprintステートメントを入れると、stringyがnilではないことがわかります。 otherVCのラベルは正しく設定されているので、何がnil値を与えているのか分かりません。

+1

はあなたを持っています値を文字列として渡し、AlertVCのviewDidLoadにラベルを設定しようとしましたか?ビューコントローラを表示する前にあなたのラベルがまだnilだと思う。 – mat

答えて

1

あなたのビューコントローラを表示するまで、あなたのラベルが利用可能とは思われません。代わりに文字列を渡し、AlertVCviewDidLoadメソッドでラベルテキストを設定します。

var stringy:String? 

、あなたがviewDidLoadにテキストラベルを設定することができ、この時点で、あなたのコード

@IBAction func ButtonAction(_ sender: Any) { 

     let otherVC = self.storyboard?.instantiateViewController(withIdentifier: "AlertVC") as! AlertVC 
     otherVC.modalPresentationStyle = .overCurrentContext 
     otherVC.delegate = self 
     otherVC.stringy = stringy //you pass the string instead of setting the label text 
     self.present(otherVC, animated: true, completion: nil)//presents the other VC modally 

    } 

を変更:文字列を宣言し、あなたのAlertVC

self.label.text = self.stringy 
+0

文字列をどのように渡すのですか?私は 'override func prepare(for segue:)'のようなものを使用するのに慣れていますが、本当のセグがないので、VCはモーダルで表示されます。どのように情報を渡しますか? –

+0

更新された回答を確認する – mat

関連する問題