Objective C - Add a Category

Categories provide the ability to add functionality to an object without subclassing or changing the actual object. Usually, categories are used to add methods to an existing class. In this tutorial, we will add a category to the UISwitch class, which enables us to change the colors of our switch.

Open Xcode and create a new Single View Application. For product name, use CategoryDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag a UISwitch to the main View. The main View should look like this.

Select the assistant editor and open ViewController.m. Ctrl and drag from the switch to the interface section and create a IBOutlet property.

select the New -> File option and select the "Objective-C category" template. Name the category CustomSwitch and UISwitch as the class that will take the category.

This creates two files UISwitch+CustomSwitch.h and UISwitch+CustomSwitch.m

Navigate to UISwitch+CustomSwitch.h and add a method declaration

@interface UISwitch (CustomSwitch)

+ (id)UISwitchWithTintColor:(UIColor *)tintColor onTintColor:(UIColor *)onTintColor thumbTintColor:(UIColor *)thumbTintColor;


Next, go to UISwitch+CustomSwitch.m and implement the UISwitchWithTintColor:onTintColor:thumbTintColor method.

+ (id)UISwitchWithTintColor:(UIColor *)tintColor onTintColor:(UIColor *)onTintColor thumbTintColor:(UIColor *)thumbTintColor
  [[UISwitch appearance] setOnTintColor:onTintColor];
  [[UISwitch appearance] setTintColor:tintColor];
  [[UISwitch appearance] setThumbTintColor:thumbTintColor];

  return self;

Here we simply set the colors of the UISwitch. Go to the ViewController.m file and import our Category Header file.

#import "UISwitch+CustomSwitch.h"

Change the viewDidLoad method.

- (void)viewDidLoad
  [super viewDidLoad];

  self.mySwitch = [UISwitch UISwitchWithTintColor:[UIColor redColor] onTintColor:[UIColor blueColor] thumbTintColor:[UIColor greenColor]];

We make a call to our method of the category, this will customize the colors of our UISwitch. Build and Run, and flip the switch to see the custom colors.

You can download the source code of the CategoryDemo at the ioscreator repository on github.