Search code examples
objective-cswiftstoryboardsegueuistoryboardsegue

Subclassing in Storyboard


When I override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?), I get the destination view controller via

let viewController = segue.destinationViewController as! VehicleDetailViewController

Works fine so far.

But how can I substitute VehicleDetailViewController with some subclass of SomeDetailViewController, e.g. CarDetailViewController or BikeDetailViewController?

So the code (snippet) should look like

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "SegueID" {
        let indexPath = tableView.indexPathForSelectedRow!
        let vehicle = Vehicle[indexPath.row]
        switch vehicle {
        case is Car:
            let viewController = segue.destinationViewController as! CarDetailViewController

        case is Bike:
            let viewController = segue.destinationViewController as! BikeDetailViewController
        }
    }
}

but Xcode tells me that the cast is not allowed:

Could not cast value of type 'SomeApp.VecicleDetailViewController' (0x10ede2220) to 'SomeApp.CarSensorDetailViewController' (0x10ede2310).

Also help in Objective-C is welcome, because the question is not language-related.


Solution

  • A segue instantiates a specific class. If you want multiple subclasses of SomeDetailViewController then you will need to layout multiple viewControllers in your Storyboard and create multiple segues.

    You can do this by control-dragging from the viewController icon at the top of your viewController to each viewController that is a subclass of SomeDetailViewController. Then add identifiers to the segues and call them with performSegueWithIdentifier in didSelectRowAtIndexPath.

    Another way to do this would be to create multiple prototype cells for your tableView, with each one wired to the specific viewController it is segueing to.