Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 that :

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

The methods viewDidLoad and loadView are never called !!!

Do you know why and if there is some way of doing what I want.

Thanks in advance.

like image 605
Fred Avatar asked Nov 18 '14 14:11

Fred


1 Answers

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

The workaround would be using the class as a property. something like this:

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)
like image 135
rintaro Avatar answered Oct 12 '22 21:10

rintaro