I need to run the common function to all UIViewcontroller without manually specifying "self.function()"
Asked
Active
Viewed 238 times
-3
-
When do you want it to run? – David S. Sep 15 '18 at 11:27
-
automatically need run for each UIviewcontroller did load. but won't specify function name. – Leena Sep 15 '18 at 11:31
-
Create BaseViewController of type UIViewController, override all the behavior needed. Then create all the rest of your vcs as subclasses of BaseViewController. – inokey Sep 15 '18 at 11:45
3 Answers
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.
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