Reputation: 6381
I am developing in Swift.
And the following picture is my storyboard.
There has a Main view. The Main view will change the view to the Scan view and also pass the data to the Scan view
when press the Scan (Right Bar button item).
And the identifier of the StoryBoard Segue is ScanView
I use the following code to pass the data from Main to the Scan
When press the Scan (Right Bar button item).
self.performSegueWithIdentifier("ScanView", sender: self)
And pass the data to the next view
//prepare jumping to next page
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier=="ScanView"){
let desViewController = segue.destinationViewController as! ScanViewController
desViewController.myCenteralManager = myCenteralManager
}
}
And it will crash at let desViewController = segue.destinationViewController as! ScanViewController
and show the error like the following :
Could not cast value of type 'UINavigationController' (0x3960e0a8) to 'BLEConnect.ViewController' (0x5514c).
Can someone teach me how to solve the issue ? Thanks in advance.
Upvotes: 1
Views: 635
Reputation: 11
You can embed your navigation controller to the main ViewController and perform a segue as you have done above. That should solve the problem.
The error message is displayed because you have type casted Navigation Controller instead of Scan ViewController .
Upvotes: 0
Reputation: 3093
Your NavigationController
is (probably) in the wrong place in Interface Builder. Right now, when you segue, you are going to the UINavigationController
and not the ScanViewController
like you expect. This is why the cast fails, because you are trying to force the UINavigationController
to be a ScanViewController
.
To fix this, you should place your MainViewController
in the UINavigationController
and then segue straight to your ScanViewController
.
This guide shows exactly how you can use Interface Builder, UINavigationController, and segues to achieve what you're trying to do.
Upvotes: 0
Reputation: 1379
The error message are pretty clear, you try to get segue.destinationViewController
as ScanViewController
while in fact it is a navigation controller. You need to get the navigation controller first and then use its topViewController
property to get your targeted view controller.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier=="ScanView") {
if let navController: UINavigationController = segue.destinationViewController as? UINavigationController {
if let desViewController: ScanViewController = navController.topViewController as? ScanViewController {
desViewController.myCenteralManager = myCenteralManager
}
}
}
}
Upvotes: 1