Swift creating a generic UIViewController

I am trying to create a class like this:

class MyClass<T:UIView>: UIViewController{


    override init()
    {
        super.init(nibName: nil, bundle: nil);
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func loadView() {
        self.view = T();
        println("loadView")
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        println("viewDidLoad")
    }

}

      

When I want to use my class like this:

self.navigationController?.pushViewController(MyClass<UIView>(), animated: true)

      

The viewDidLoad and loadView methods are never called !!!

Do you know why and if there is some way to do what I want.

Thanks in advance.

+3


source to share


1 answer


As the OP mentioned in the comments, the Generic class cannot be represented correctly in Objective-C.

The workaround would be to use the class as a property. something like that:



class MyClass: UIViewController{

    let viewCls:UIView.Type

    init(viewCls:UIView.Type = UIView.self) {
        self.viewCls = viewCls
        super.init(nibName: nil, bundle: nil);
    }

    required init(coder aDecoder: NSCoder) {
        self.viewCls = UIView.self
        super.init(coder: aDecoder)
    }

    override func loadView() {
        self.view = viewCls();
        println("loadView")
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        println("viewDidLoad")
    }

}

// and then
self.navigationController?.pushViewController(MyClass(viewCls: UIView.self), animated: true)

      

+3


source







All Articles