Search code examples
swiftuiviewcontrolleruitabbarcontrolleriad

Call a method from anywhere in a tabbar application swift


I have a tabBar application with 4 different ViewControllers. Is it possible to call the same method from all the 4 views, where do I have to put the method? For the record it is just a call to show a iAd banner.

Thanks


Solution

  • This would work. Create a custom subclass of UITabBarController. Put your function in there. Be sure the change the class of the TabBarController in the Storyboard to CustomTabBarController.

    class CustomTabBarController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view.
        }
    
        func myFunctionToCallFromAnywhere() {
            print("Hey, it works")
        }
    }
    

    Then in your viewControllers that are managed by your TabBarController you can call the function like this:

    (self.tabBarController as? CustomTabBarController)?.myFunctionToCallFromAnywhere()