SpacemanDeMars SpacemanDeMars - 1 month ago 14
Swift Question

UITabBarController subclass methods not available on child view controllers?

I am trying to call a custom method on my

UITabBarController
subclass from within one of the child view controllers. I have instantiated my
CustomTabBarController
class as the root view controller in
AppDelegate.swift
, however, the
.tabBarController
property on my child view controllers is of the class
UITabBarController
instead of
CustomTabBarController
.

Why does this happen? Is it possible to have the
.tabBarController
property on my view controllers reflect my subclass instead of the default
UITabBarController
class?

Here is my subclass:

import UIKit

class CustomTabBarController: UITabBarController, UITabBarControllerDelegate, LoginControllerDelegate {

let defaults = UserDefaults.standard

override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
setupViews()
}

override func viewDidAppear(_ animated: Bool) {
checkLoginStatus()
}

func checkLoginStatus() {
if defaults.bool(forKey: "isLoggedIn") == false {
let loginController = LoginController()
loginController.delegate = self
present(loginController, animated: true, completion: nil)
}
}

func loginControllerDidDismiss() {
print("Delegation is working...")
}

func setupViews() {
let homeController = HomeController()
homeController.tabBarItem = CustomTabBarItem(title: "Home", imageNames: ["courthouse-icon-unselected", "courthouse-icon"])
let homeNavController = UINavigationController(rootViewController: homeController)
homeNavController.navigationBar.applyCustomStyle()

tabBar.tintColor = UIColor(red:0.18, green:0.34, blue:0.65, alpha:1.00)
self.setViewControllers([homeNavController], animated: true)
}

func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
print(viewController.title)
return true
}

}


In my view controller, I would like to access this class like so:

import UIKit

class HomeController: ListController {

override func viewDidLoad() {
super.viewDidLoad()
self.title = "Home"
self.tabBarController??? // Right now this is a UITabBarController, but I would like to it be a CustomTabBarController
}

}

Answer

The best approach is to test whether it's what you believe it to be and cast it so that the compiler knows the correct class.

e.g.:

    if let custom = self.tabBarController as? CustomTabBarController {
        custom.checkLoginStatus()
    } else {
        print("Unexpected controller \(self.tabBarController)")
    }