-3

I need to run the common function to all UIViewcontroller without manually specifying "self.function()"

Leena
  • 43
  • 1
  • 7

3 Answers3

2

I think it is not possible to swizzle the viewDidload() in swift4 although it is possible earlier by swizzling, instead you can do it by inheritance

Class BaseVC: UIViewController {
    func viewDidLoad() {
    super.viewDidLoad() 
  /// customization here … e.g self.function() 
    }
}

Class CustomVC: BaseVC {
 func viewDidLoad() {
    super.viewDidLoad() 
     // you had called self.function no need to do it again 
    }
}
SuryaKantSharma
  • 1,113
  • 12
  • 27
-1

Just add your custom methods to the UIViewController using extension:

extension UIViewController {

   func customFunc() {
      print("Custom func is called")
   }
}

Now, inside every class that inherits from UIViewController you can easily access this func:

class MainVC: UIViewController {

   override func viewDidLoad() {
    super.viewDidLoad()

   //call your func
   customFunc()
   }

}
Starsky
  • 1,829
  • 18
  • 25
  • I guess I got the downvote because the OP asked not to call the function manually but run it automatically at the viewDidLoad(). Fair enough. Most probably I didn't notice this one detail at the time of writing the solution. Oops. – Starsky Dec 07 '18 at 06:30
-3

The only way to override a function in a class you cannot modify (such as the UIViewController base class) is to use method swizzling.

How to swizzle init in Swift

You an use this technique to swizzle viewDidLoad or viewDidAppear.

Most of the time though, you should just subclass the UIViewController for your needs and call your function in the lifecycle method override.

David S.
  • 6,567
  • 1
  • 25
  • 45