Timering

Purp

UIColor Subclass - change Color with key

If your App uses a lot of colors, and you need to write conditions in all View Controller to define which color to display, it should all be completed within UIColor subclass. So instead e dozens of lines of code in every ViewController, you can write only 2-3 lines code. Now I show it in Objective-C. 

Steps

  1. Create Button programmatically and a random number
  2. Create UIColor Subclass
  3. Write a SetColor condition code in UIColor subclass
  4. Call the UIColor SetColor from ViewController
  5. Test your App

Video

1. create UIButton programmatically and a random number

Create myButton in ViewController.h:

UIColor Subclass Tutorial Objective C 1

Then add some basic parameter for your UiButton, such as a frame, backgroundColor and target action which will change the color. Do with this code:

2. Create UIColor Subclass

Right click at the files, add new Cocoa Class, name:"Colors", and type: "UIColor".

UIColor Subclass Tutorial Objective C 2

UIColor Subclass Tutorial Objective C 2

UIColor Subclass Tutorial Objective C 4

UIColor Subclass Tutorial Objective C 6

3. Write a SetColor condition code in UIColor subclass

Add this line to your Colors.h file:

And create an if condition in your m file, which can tell which color will be set, if the randomNumber is for instance 5.... Put this in your Colors.m file:

Now, you need to call this code from your ViewCotnroller.

4. Call the UIColor SetColor from ViewController

First of all import the Colors in your ViewController

UIColor Subclass Tutorial Objective C 7

After that call the SetColor method in your changeColor code with the randomNumber:

5. Test your App

Finally, just run the App, click the button, and check the numbers in log, and your button backgroundColor. For instance, you can see the randomNum is 4, the ccColorId is 4 too, and as in your condition, the 4 means that will be UIColor grayColor - as you can see in the Simulator. So easy, have fun with this and your easiest coding with some useful subclasses!

UIColor Subclass Tutorial Objective C 8

Download

Download the Xcode tutorial from Github.

NEXT

The next part of the series: Rounded UIButton with different solutions - colors, strokes with an image... and the same tutorial in Swift.

Share & Follow

If you would like to be notified of my new solutions, please subscribe to my Newsletter or my youtube channel and/ or follow me on Facebook or Twitter! Check Footer section for these opportunities!