Can't cast value of type UIViewController to PatternDetailViewController

前端 未结 8 1613
孤街浪徒
孤街浪徒 2020-12-06 04:29

Am trying to downcast a view controller to a detail view controller but can\'t. Am using Core Data (for the first time). The error is in the prepareForSegue method and reads

相关标签:
8条回答
  • 2020-12-06 04:39

    This issue can happen if you copy Storyboard files from other project and did not change the Module .

    In the above image "EmployeeApp" is the old project name and the "clientTradingApp" is the new project name

    Happy Coding :)

    0 讨论(0)
  • 2020-12-06 04:41

    My issue is:

    Not work

    let aBCViewController = UIViewController(nibName: "ABCViewController", bundle: nil) as! ABCViewController
    present(aBCViewController, animated: true, completion: nil)
    

    Work

    let aBCViewController = ABCViewController(nibName: "ABCViewController", bundle: nil)
    present(aBCViewController, animated: true, completion: nil)
    
    0 讨论(0)
  • 2020-12-06 04:51

    It looks like you are using a navigation controller judging by your viewDidLoad() in PatternDetailViewController.

    If PatternDetailViewController is embedded in a UINavigatonController then the navigation controller will be segue.destinationViewController.

    Get the PatternDetailViewController like this:

    let vc: UINavigationController = segue.destinationViewController as! UINavigationController
    let detailVC = vc.topViewController as! PatternDetailViewController
    detailVC.pattern = self.selectedPattern
    
    0 讨论(0)
  • 2020-12-06 04:56

    The problem, as you have said, is in these lines:

    if segue.identifier == "patternDetailSegue" {
        var detailViewController = segue.destinationViewController as! PatternDetailViewController 
        // Could not cast value of type 'UIViewController' to 'Patternz.PatternDetailViewController'
    

    The error message tells you that the destinationViewController of this segue is not, in fact, a PatternDetailViewController. You may think it is, but it isn't. You need to examine this segue in the storyboard and see what's really at the destination end of it.

    The fact that the error message describes it as a UIViewController makes me suspect that you forgot to enter any view controller type in this view controller's Identity inspector in the storyboard:

    Xcode Screenshot

    0 讨论(0)
  • 2020-12-06 05:00

    Adding to matt answer. Sometimes, you may also need to double check the custom class Module from the Identity inspector.

    Your view controller need to belong to a specific Module. So make sure to select a Module from the list. In my case:

    0 讨论(0)
  • 2020-12-06 05:01

    This just happened to me and I struggled for a couple hours following all the other posts here. In the end it turned out that my destination view controller file was missing the .swift extension. I hope this helps someone else!

    0 讨论(0)
提交回复
热议问题