ajrlewis
ajrlewis

Reputation: 3058

iOS (Swift) - Array of UIViewControllers

I have an array UIButtons that have a unique tag value. When a given button is pressed, I want to load and present a UIViewController that is also stored in an array of equal length.

The UIViewControllers to be presented are subclasses of a subclass of UIViewController:

class AViewController: UIViewController {}
class BViewController: AViewController {}
class CViewController: AViewController {}
class DViewController: AViewController {}
// ... etc.

I've tried storing the array of AViewController subclasses using the following:

private var array: [AViewController] = [BViewController.self, CViewController.self, DViewController.self]

but I get the error Cannot convert value of type '[BViewController].Type' to specified type '[AViewController]' for the first element.

I will then present BViewController (for instance) using the following:

let ViewController = array[button.tag].self
var viewController: AViewController
viewController = ViewController.init()
viewController.transitioningDelegate = self
viewController.modalPresentationStyle = .custom
present(viewController, animated: true)

Please let me know if this is the incorrect thought process for doing something like this please and thanks for any help.

Upvotes: 0

Views: 3673

Answers (3)

iPhoneDeveloper
iPhoneDeveloper

Reputation: 996

Alternate answer if you want to store array of view controllers as a constant.

 struct AppConstant {

       static let yourViewControllers: [AnyClass] = [AViewController.self, 
            BViewController.self, CViewController.self]
}

Upvotes: 0

Kunal Parikh
Kunal Parikh

Reputation: 19

lazy var VCArray :[UIViewController] = {
    return [VCinst(name: "firstVC"),VCinst(name: "secondVC"), VCinst(name: "thirdVC")]
}()

func VCinst(name:String) -> UIViewController {
       return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: name)
}

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100551

You need instances

private var array: [AViewController] = [BViewController(), CViewController(), DViewController()]

if the vcs are in IB , then you would do

let b = self.storyboard!.instantiateViewController(withIdentifier: "bID") as! BViewController
let c = self.storyboard!.instantiateViewController(withIdentifier: "cID") as! CViewController 
let d = self.storyboard!.instantiateViewController(withIdentifier: "dID") as! DViewController

Then

array = [b,c,d]

Upvotes: 6

Related Questions