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.
Create myButton in ViewController.h:
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:
Right click at the files, add new Cocoa Class, name:"Colors", and type: "UIColor".
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.
First of all import the Colors in your ViewController
After that call the SetColor method in your changeColor code with the randomNumber:
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!
Download the Xcode tutorial from Github.
The next part of the series: Rounded UIButton with different solutions - colors, strokes with an image... and the same tutorial in Swift.
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!