I have a segue from ViewController A to ViewController B. It uses a custom segue class RightSegue. This is the code for the RightSegue class:
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()
})
}
The view controllers are set up as shown in the image.
As can be seen, the FirstViewController contains a button which when clicked shows the SecondViewController.
The next image shows the segue's properties:
When I execute the app and press the button in FirstViewController, the app crashes with the error message:
fatal error: unexpectedly found nil while unwrapping an Optional value
I checked vc2NavController
in the RightSegue class. It has a return type of UINavigationController?
. Force unwrapping it returns nil.
As indicated in this answer (Custom Segue in Swift), I added the @objc() and ran the app. It still didn't work. The app crashes, this time giving the error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not create a segue of class '(null)''
I don't know what to do. Please help.
Edit: You need to push your second viewController for it to have a navigationController. The custom segue is what causing your problem. You need to return the navigationController, or better - read this:
http://netsplit.com/custom-ios-segues-transitions-and-animations-the-right-way
If you want to stay with the custom, this may help - Custom Push Segue removes navigation bar and tab bar in story board