How do I call a certain function from a UIViewController Here is my code file, I want to call a function say, viewController.somefunction() when a item is pressed or say when the viewController changes
import UIKit
import WebKit
class tabbarController: UITabBarController, UITabBarControllerDelegate{
override func tabBar(_ tabBar : UITabBar, didSelect item: UITabBarItem){
print("selected item")
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController){
print("calling custom function here from viewController");
}
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
}
CodePudding user response:
You need to get a reference to the view controller so you can call the function in it.
Quick example, assuming you have setup in Storyboard a TabBarController, assign its Custom Class as MyCustomTabBarController
, with two tabs - FirstTabVC
and SecondTabVC
:
class MyCustomTabBarController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
// this is called *when* the tab item is selected (tapped)
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
// safely unwrap optionals
guard let theItems = self.tabBar.items,
let idx = theItems.firstIndex(of: item),
let controllers = self.viewControllers
else { return }
if let vc = controllers[idx] as? FirstTabVC {
vc.someFunctionInFirst("From didSelect item")
}
if let vc = controllers[idx] as? SecondTabVC {
vc.someFunctionInSecond("From didSelect item")
}
}
// this is called when the tab's ViewController is selected (*after* the tab item is selected (tapped))
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if let vc = viewController as? FirstTabVC {
vc.someFunctionInFirst("From didSelect viewController")
}
if let vc = viewController as? SecondTabVC {
vc.someFunctionInSecond("From didSelect viewController")
}
}
}
class FirstTabVC: UIViewController {
public func someFunctionInFirst(_ str: String) {
print("In First Tab VC: ", str)
}
}
class SecondTabVC: UIViewController {
public func someFunctionInSecond(_ str: String) {
print("In Second Tab VC: ", str)
}
}