How to create a Radial Gradient in Objective-C (iOS)


I got bored of working on my PC software project today and decided to dust off my iOS / Objective-C skills again. I’ve not had too many opportunities to sharpen my Objective-C skills and I’m even learning Swift 2 at the moment.

In my PC app, I created a beautiful login screen using a radial-gradient as the background image and I thought: why not recreate something similar using Objective-C. So, I went hunting. StackOverflow and the Apple Developer site led me to the solution below.

To create the radial background, the approach I used was to create a custom UIVew class (obviously, this class extends the UIView class). To do this, from your XCode project, select “File” > “New…” > “File”

Screen Shot 2015-10-27 at 13.58.15

When prompted, select “Cocoa Touch Class” and click “Next”

Screen Shot 2015-10-27 at 13.58.33

Enter the name of your class and make sure that it extends the  UIView  class.

Screen Shot 2015-10-27 at 13.58.33

This done, place the following code in the .m file (the class implementation) for your UIView class.

Make sure to replace  OORadialGradientView  with the name of your own class.

This would give you a class that, by default, adds a radial gradient (from yellow to orange) to any view that it’s attached to. Now, this is all nice and dandy but you won’t see anything yet. To see the effects of your gradient, you need to make use of the class.

Open your storyboard and then do one of two things. Either click directly on the blank space within the default ViewController or, open the Document outline. The document outline button is at the bottom left corner of the Standard Editor. Click this icon and in the Document Outline, select the first “View” element making sure you achieve the following effect:

Screen Shot 2015-10-27 at 14.10.28

This done, move to the identity inspector on the right side of your IDE.

Screen Shot 2015-10-27 at 14.12.24

In the Custom Class field (where “UIView” is written), type in the name of your newly created class. And voila! You’re done.

You can checkout your handiwork by running the project in any simulator of your choice.

Screen Shot 2015-10-27 at 14.15.30

And when rotated in landscape mode:

Screen Shot 2015-10-27 at 14.15.43

Feel free to tweak the numerical values in your Gradient class to adjust the display and colors as you please.

I’ve added this class and would be adding quite a few more to this github project.