2016-06-23 8 views
0

親ビューコントローラからコンテナビューコントローラのラベルにアクセスしたいとします。私は以下を試しました:Swift 2の親コントローラからコンテナビューコントローラにアクセス

prepareForSegueは親ビューコントローラの関数です。 ViewController2はコンテナビューコントローラです。 parin2は、コンテナビューコントローラ内のラベルの名前です。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) 
{ 
    let vc1 = segue.destinationViewController as! ViewController2; 
    vc1.parin2.text=String("helo"); 
} 

これは、次のエラーを与える:

fatal error: unexpectedly found nil while unwrapping an Optional value 

答えて

1

あなたは行がエラーの原因となったが、私の推測では、それが(ちなみに、省略してくださいlet vc1 = segue.destinationViewController as! ViewController2だったということですかを正確に言いませんでした';スウィフトの中で);宛先ビューコントローラがViewController2ではないため、as!が失敗しているように見えます。これを確認するには、その行にブレークポイントを設定し、セグのdestinationViewControllerプロパティを調べて、どのような種類のビューコントローラであるかを確認します。 で、ViewController2でない場合は、ストーリーボードに問題があります。ストーリーボードの目的地のクラスがViewController2ではありません。

prepareForSegueを処理するためのより良いパターンは以下の通りです:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { 
    // ALWAYS check the segue identifier first! If you forgot to put one on 
    // your segue in the storyboard, then you should see a compiler warning. 
    switch segue.identifier { 
    case "SegueToViewController2": 
     guard let destination = segue.destinationViewController as? ViewController2 else { 
      // handle the error somehow 
      return 
     } 
    default: 
     // What happens when the segue's identifier doesn't match any of the 
     // ones that you expected? 
    } 
} 
関連する問題