简体   繁体   中英

Subclassing a UIViewController class

My app has an UITabBar . Most of the tabs have similar functionality, though they differ in important ways.
To avoid code duplication, I'd like to create a class ( BaseViewController ) which handles the similar functionality, and use subclasses of this ( FirstViewController , Second etc) to control the unique functions.

What would be the best way of doing this?
One problem I envisage is if I create xibs and view controllers, how do I connect up elements in the xib to the base view controller?

                   > FirstTabViewController
BaseViewController > SecondTabViewController
                   > ThirdTabViewController

If the BaseViewController has IBOutlet properties they will behave just the same in an inherited class in Interface Builder. All you will need to do is drag your connections over.

FirstTabViewController, SecondTabViewController, et al. will inherit the outlets and actions of BaseViewController, so you'll connect UI elements to your subclasses just as you would to the base class.

You can also get your base class to create things programatically for you. Eg nav bar buttons/background images.

Essentially you'll need to create a UIViewController subclass which would be your base. We'll call this MyBaseVC.

Next you'll go ahead and create your other three view controller classes (MyVC1, MyVC2, MyVC3) just like you did the first one. In their header files replace, UIViewController with MyBaseVC. These will now be a subclass of MyBaseVC.

Then in the identity inspector of your Interface Builder file you'll set the Custom Class of any View Controller you create to MyVC1, MyVC2, MyVC3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM