2015-10-14 89 views
1

我目前正在嘗試重新工作this navigation dropdown menu,以便下拉菜單僅佔用窗口的下半部分。嘗試獲取對容器視圖控制器的引用

這是我的故事板設置:

storyboard

不要擔心外來標籤/按鈕。我只是想顯示不同的視圖控制器/連接與此圖片。)

我有一個問題獲取對容器視圖控制器的引用,以便我可以定義框架。這就是我現在得到:

private var navigationController: UINavigationController? 

,並聲明該變量時:

self.navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController?.presentedViewController?.presentedViewController?.childViewControllers[0] as? UINavigationController 
println(self.navigationController!.nameOfClass) // logs: UINavigationController 
self.navigationController = self.navigationController!.topMostViewController?.navigationController // 
println(self.navigationController!.nameOfClass) // logs: Optional(<UINavigationController: 0x7f8681e7b5f0>)UINavigationController 

這裏就是我得到的錯誤 - 試圖定義下拉菜單視圖幀時:

var frame = CGRectMake(0, 0, titleSize.width + (self.configuration.arrowPadding + self.configuration.arrowImage.size.width)*2, self.navigationController!.navigationBar.frame.height) 

我得到的錯誤:

fatal error: unexpectedly found nil while unwrapping an Optional value.

我知道這意味着什麼,但我爲什麼價值爲零而感到困惑。因爲當我記錄self.navigationController的類名時,我得到了正確的導航控制器。

而且,這裏是爲nameOfClass和topMostViewController參考:我試圖要簡潔,同時還提供足夠的信息

extension UIViewController { 
    var topPresentedViewController: UIViewController? { 
    var target: UIViewController? = self 
    while (target?.presentedViewController != nil) { 
     target = target?.presentedViewController 
    } 
    print(target) 
    return target 
    } 
    var topVisibleViewController: UIViewController? { 
    if let navigation = self as? UINavigationController { 
     if let visibleViewController = navigation.visibleViewController { 
      return visibleViewController.topVisibleViewController 
     } 
    } 
    if let tab = self as? UITabBarController { 
     if let selectedViewController = tab.selectedViewController { 
      return selectedViewController.topVisibleViewController 
     } 
    } 
    return self 
    } 
    var topMostViewController: UIViewController? { 
    return self.topPresentedViewController?.topVisibleViewController 
    } 
} 

public extension NSObject{ 
    public class var nameOfClass: String{ 
    return NSStringFromClass(self).componentsSeparatedByString(".").last! 
    } 
    public var nameOfClass: String{ 
    return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last! 
    } 
} 

,但如果需要,我可以張貼整個項目。任何幫助將不勝感激:)

回答

0

UIViewController已經定義了一個navigationController財產https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instp/UIViewController/navigationController

我不知道你的代碼是不self.navigationController!.navigationBar ...但也許它的範圍已經得到它的那名可可的財產,而不是你自己的。我不知道爲什麼編譯器會讓你在不發出警告的情況下重新聲明一個同名的屬性,關於你的私有屬性?

嘗試爲您的財產使用不同的名稱。另外,請看UIViewControllerpresentingViewController,因爲也許你可以使用它。

+0

呃,只是想通了> _ < 當我指定框架的寬度,特別是arrowimage.size.width屬性時,我得到了零。原來,我將對圖像的引用複製到我的項目中,而不是實際的圖像本身。不能相信我花了一整天的時間來堅持下去! 繼續.. – jvolen2

相關問題