Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController extension not allowing to override view related functions in Swift?

While trying to implement an extension for UIViewController I realise that there is no normal way, or is not allowed to override this functions (even when they are available for UICollectionViewController and UITableViewController):

extension UIViewController{
  public override func viewWillAppear(){
    super.viewWillAppear()
    //do some stuff
 }
}

I realise that there is no normal way, or is not allowed to override this functions (even when they are available for UICollectionViewController and UITableViewController):

  • viewDidLoad
  • viewWillLoad
  • viewWillAppear
  • viewDidAppear

There is some way to do this? I would like to have some implementation there and working for every UIViewController on my app... All in just one place.

Please, note that I don't want to make a new class subclassing UIViewController, overriding those methods and making my controller to extend it. This is the obvious and simplest solution, but this do not satisfy what I'm trying to do.

I'm using swift 1.2 in XCode 6.3

like image 532
Hugo Alonso Avatar asked Apr 29 '15 18:04

Hugo Alonso


1 Answers

What you are trying to do is similar to what done by this code:

class MyClass {
    func myFunc() {}
}

extension MyClass {
    override func myFunc() {}
}

The 4 methods that you are trying to override are defined in UIViewController, and not to one of its superclasses. And you can't override a method which is defined in the same class.

Update

I can think of 2 different ways to solve the problem - the first is the one you don't want (subclassing UIViewController).

The other one is method swizzling - I never used it so I don't want to provide you inaccurate info. Maybe it's worth reading this article by Nate Cook, which incidentally is showing an example of replacing viewWillAppear.

like image 124
Antonio Avatar answered Oct 14 '22 07:10

Antonio