Swift 2.0中的自定义Segue:destinationViewController的navigationController属性返回nil

时间:2016-03-02 06:14:41

标签: ios uiviewcontroller swift2 segue uistoryboardsegue

我有一个从ViewController A到ViewController B的segue。它使用自定义segue类RightSegue。这是RightSegue类的代码:

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)''

我不知道该怎么做。请帮忙。

1 个答案:

答案 0 :(得分: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