2011-12-21 2 views
10

ShareKit에서 코드는 rootViewController가 어디에 있는지 확인하여 모달 뷰를 표시 할 수 있어야합니다. 어떤 이유로 iOS 5에서 코드가 실패합니다.iOS에서 rootViewController 찾기

// Try to find the root view controller programmically 

    // Find the top window (that is not an alert view or other window) 
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow]; 
    if (topWindow.windowLevel != UIWindowLevelNormal) 
    { 
     NSArray *windows = [[UIApplication sharedApplication] windows]; 
     for(topWindow in windows) 
     { 
      if (topWindow.windowLevel == UIWindowLevelNormal) 
       break; 
     } 
    } 

    UIView *rootView = [[topWindow subviews] objectAtIndex:0]; 
    id nextResponder = [rootView nextResponder]; 

    if ([nextResponder isKindOfClass:[UIViewController class]]) 
     self.rootViewController = nextResponder; 

    else 
     NSAssert(NO, @"ShareKit: Could not find a root view controller. You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER]."); 

이것은 어설 션을 때리는 것입니다.

단순히 다음 코드를 사용하는 것이 잘못된 것입니까?

rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController]; 

이것은 잘 작동하는 것 같습니다. 어떤 조건 하에서 실패할까요?

답변

27

window.rootViewController b/c에 의존 할 수 있는지 확실하지 않습니다. 설정하지 않아도됩니다. 창에 하위보기를 추가하기 만하면됩니다.

id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder]; 
+0

:

/// EZSwiftExtensions - Gives you the VC on top so you can easily push your popups public var topMostVC: UIViewController? { var presentedVC = UIApplication.sharedApplication().keyWindow?.rootViewController while let pVC = presentedVC?.presentedViewController { presentedVC = pVC } if presentedVC == nil { print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.") } return presentedVC } 

그것의 표준 기능으로 포함 다음은 잘 작동하는 것 같았다 감사. 이 경우 rootViewController가 설정됩니다. 나에게이 설정만으로이 ShareKit 코드의 목적을 위해 자동으로 rootViewController가되는 것은 확실하지 않다. 이것은 보편적 인 응용 프로그램이며, iPhone 코드에서 rootViewController는 서브 클래 싱 된 UITabBarController입니다. 나는 또한 UIAlertView와 UIView를 서브 윈도우로 애플리케이션 윈도우에 추가했다고 덧붙여 야한다. (나는 tabbarcontroller에서 어떤 뷰가 보여지고 있는지에 관계없이 둘 중 하나 또는 둘 다를 보여줄 수 있습니다.) 코드는 UIAlertView를 objectAtIndex : 0으로 반환합니다. 나머지 부분을 반복 할 수 있습니다. – Jim

+1

앱에 설정하면 확실히 작동합니다. 나는 당신이'window.rootViewController'가 설정되어 있지 않은 곳에서 사용할 다른 라이브러리를 생성하고 있는지 알지 못했습니다. – XJones

+0

@XJones, window.rootViewController가 설정되지 않은 경우 어떻게해야합니까? 현재보기 컨트롤러를 안정적으로 얻을 수있는 다른 방법이 있습니까? – Zennichimaro

관련 문제