user1314147
user1314147

Reputation: 362

Accessing UITabBarController variable in Swift

I want to be able to subclass UITabBarController so I can add a variable and access it from the view controllers that it manages. Is this possible or should I move the var to a separate class/ app delegate? Thanks!

Upvotes: 0

Views: 1233

Answers (1)

Andrew Flo
Andrew Flo

Reputation: 101

Yes definitely possible. For example, I'll use the class name CustomTabBarController so create a new Swift file using the template iOS / Cocoa Touch Class named CustomTabBarController.swift and in the new file dialog have it subclass UITabBarController.

You now have your custom class that inherits UITabBarController. You can add your properties and methods.

Now in your Storyboard add a UITabBarController (or select your existing one). In the inspector pane, click the Identity tab and set the custom class to CustomTabBarController.

Now to access your property or method in a ViewController that's in your CustomTabBarController, you could use something like this within that ViewController:

if let customTabBarController = self.tabBarController as? CustomTabBarController {
     print(customTabBarController.variableName)
}

Upvotes: 1

Related Questions