2016-03-02 51 views
1

我有一個從ViewController A到ViewController B的Segue。它使用自定義的Segue類RightSegue。這是RightSegue類的代碼:Swift 2.0自定義塞格:destinationViewController的navigationController屬性返回零

class RightSegue: UIStoryboardSegue { 

override func perform() { 

    // Assign source and destination view controllers to local variables. 
    let vc1: UIViewController = self.sourceViewController 
    let vc2: UIViewController = self.destinationViewController 

    // Get screen width and height. 
    let screenWidth = UIScreen.mainScreen().bounds.size.width 
    let screenHeight = UIScreen.mainScreen().bounds.size.height 

    // get the source view controller's frame. 
    let vc1Frame = vc1.view.frame 

    let vc2NavController = vc2.navigationController 
    let vc2NavFrameHeight = vc2NavController!.navigationBar.frame.size.height 

    // Specify the initial position of the destination view. (x, y, width, height) 
    vc2.view.frame = CGRectMake(screenWidth, vc2NavFrameHeight, screenWidth, screenHeight) 

    // Push the destinationViewController onto sourceViewController. 
    vc1.navigationController!.pushViewController(vc2, animated: false) 

    // Specify the initial position of the source view. Add destination view as a subview of the source view. 
    vc1.view.frame = CGRectMake(vc1.view.frame.origin.x, vc1.view.frame.origin.y, screenWidth, vc1Frame.size.height) 
    vc2.navigationController?.view!.addSubview(vc1.view!) 

    // Animate! 
    UIView.animateWithDuration(0.25, animations: {() -> Void in 

     vc1.view.frame = CGRectMake(-screenWidth, vc1.view.frame.origin.y, vc1.view.frame.size.width, vc1.view.frame.size.height) 
     vc2.view.frame = CGRectMake(0.0, 0.0, vc2.view.frame.size.width, vc2.view.frame.size.height) 

     }, completion: {(finished: Bool) -> Void in 

      vc1.view!.removeFromSuperview() 

    }) 

} 

視圖控制器的設置如圖所示。

two view controllers with custom segue

如可以看到的,所述FirstViewController包含當點擊顯示SecondViewController的按鈕。

的下一圖像顯示SEGUE的屬性:

Custom Segue properties

當我執行該應用並按下FirstViewController按鈕,與該錯誤消息的應用程序崩潰:

fatal error: unexpectedly found nil while unwrapping an Optional value 

我檢查RightSegue類中的vc2NavController。它有一個返回類型UINavigationController?。強制解包返回nil。

正如此答案(Custom Segue in Swift)所示,我添加了@objc()並運行了該應用程序。它仍然沒有工作。該應用程序崩潰,這次給出了錯誤:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not create a segue of class '(null)'' 

我不知道該怎麼做。請幫忙。

回答

3

編輯: 你需要推你的第二個viewController爲它有一個navigationController。 自定義segue是什麼導致您的問題。您需要返回navigationController,或更好 - 這樣說的:如果你想留在定製

http://netsplit.com/custom-ios-segues-transitions-and-animations-the-right-way

,這可能會幫助 - Custom Push Segue removes navigation bar and tab bar in story board

+0

我想這只是現在,它拋出一個錯誤'無法將類型'Custom_Segue.SecondViewController'(0x1035872a0)的值轉換爲'UINavigationController'(0x104c87588).' –

+0

我的錯誤,我以爲你有一個導航控制器作爲第二個視圖。 – Roee84

+0

查看編輯答案 – Roee84