2016-06-23 5 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!이 실패한 것 같습니다. 이를 확인하려면 해당 라인에 중단 점을 설정 한 다음 segue의 destinationViewController 속성을 검사하여 어떤 종류의보기 컨트롤러인지 확인하십시오. 이 아니고 인 경우 ViewController2 인 경우 스토리 보드에 문제가있는 것입니다. 스토리 보드에서 목적지의 클래스가 ViewController2이 아니거나 예상하지 못한 세그먼트가 표시됩니다.

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? 
    } 
} 
:

prepareForSegue을 처리하기위한 더 나은 패턴은 다음과 같다

관련 문제