i have 3 buttons, 3 Classes and 3 Viewcontrollers same UI, only different values. so i want to do 3 buttons showed 1 Viewcontrollers but used different Classes.
My logic: when pressing the button > set class > present vc
@IBAction func openTest(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "ExSim")
// i want to change class here
present(vc, animated: true)
}
CodePudding user response:
You have a basic misunderstanding. When you add a view controller to a storyboard, you tell the storyboard what subclass of view controller you are adding, and give it a unique identifier. Any time you instantiate a view controller from your storyboard using a specific identifier, you will always get a view controller of the subclass that’s defined in the storyboard. You can’t fetch a view controller from a storyboard and then transform it to a different class.
If you have 3 different screens that have have the same UI but different contents, you should use a model object to describe the contents that view controller displays. Always use the same identifier to instantiate it, and install a different model object into it depending on which button is pressed. Have the view controller load its contents into its views from the model object.
If you don’t know what a model object is, you need to read up on design patterns like MVC and MVVM, and maybe try a few tutorials that create apps using the MVC and MVVM design patterns