Search code examples
swiftswift2ios9ios-frameworks

iOS: Passing Parameters to private Framework while Initializing a UIViewController


I am trying to create a custom framework that I can use across my apps. When I instantiate my first ViewController from my framework in the app, I would like to pass in two parameters.

import UIKit

public class NewVC: UIViewController {
    public var startColor: String?
    public var endColor: String?

    public required init(startColor: String, endColor: String) {
        self.startColor = startColor
        self.endColor = endColor
        super.init(nibName: "sb", bundle: nil)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
}

Now, I am trying to instantiate NewVC in my AppDelegate:

import NewVCFramework
//...
let vc = NewVC(startColor:"00ff33a", endColor:"ff0c756")
let s = UIStoryboard(name: "sb", bundle: NSBundle(forClass: vc))
//I get an error on the line above that points at vc
self.window?.rootViewController = s.instantiateInitialViewController()

Below is the error that I get:

Error:  Cannot convert value of type 'NewVC' to expected argument type 'AnyClass' (aka 'AnObject.Type')

Solution

  • You are passing NewVC instance to the UIStoryboard init method, that expect class. Use NewVC.self instead.

    Also, if you use storyboard, init?(coder aDecoder: NSCoder) will be called instead of your custom init. You can provide startColor and endColor values after view controller instance creation

    Code below should fix your problem:

    import NewVCFramework
    //...
    let s = UIStoryboard(name: "sb", bundle: NSBundle(forClass: NewVC.self))
    let vc = s.instantiateInitialViewController() as !NewVC // Will call init?(coder aDecoder: NSCoder) for NewVC
    vc.startColor = "00ff33a"
    vc.endColor = "ff0c756"
    self.window?.rootViewController = vc