aroooo
aroooo

Reputation: 5056

Swift3: Casting UIViewController Subclass Fails

I have a ViewController (BViewController) that's inheriting from another UIViewController Subclass (AViewController). (The reason I want to do this is I'm reusing the same view in storyboard 3+ times for different screens.)

When I call:

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "AViewController") as! BViewController
        self.show(vc, sender: self)

I get this error:

Could not cast value of type 'test.AViewController' (0x10d08b478) to 'test.BViewController' (0x10d08b3f0).

Here are my subclasses, they have nothing in them.

class AViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

-

class BViewController: AViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

The class in Storyboard is set to AViewController because I'm trying to share IBOutlets across all children without recreating the views. There is only one View Controller Scene in my UIStoryboard.

Upvotes: 0

Views: 729

Answers (3)

aroooo
aroooo

Reputation: 5056

According to the answer in this thread, it isn't possible to reuse a single UIViewController Scene with multiple subclasses with UIStoryBoard. It is however possible with nib files.

How to use single storyboard uiviewcontroller for multiple subclass

Upvotes: 1

Marie Dm
Marie Dm

Reputation: 2727

You probably don't put the right view controller identifier:

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "BViewController") as! BViewController
self.show(vc, sender: self)

(BViewController instead of AViewController)

EDIT: Here's an example: I have a SignupVC view controller in my storyboard, but its storyboard ID is "signup_vc"

enter image description here

Upvotes: 0

kemkriszt
kemkriszt

Reputation: 290

You have to set your view controller's class to BViewController in your storyboard

Upvotes: 0

Related Questions