Building a custom Dashboard-like UIButton
As part of the Parking Mobility iPhone app I’ve been building, I wanted to integrate a simple “Quick Start” help guide to show people how to use the app without being intrusive. I wanted to use the project’s branding as much as possible, and give the user a feeling like they haven’t left the main portion of the app. So I wanted the user to be comfortable with it, and always have a quick way to close the help window to get back to the app.
In the end I created a little Close button in the top-left corner to mimic the behaviour of the Mac OS X Dashboard widgets. But I didn’t want to simply add a static image since those don’t scale easily. Plus I wanted to learn more about native drawing using Core Animation and Quartz2D.
The end result is actually really simple. I subclassed the UIButton class, and overrode the drawRect: method to use some native drawing primitives.
Reading through the source code, you can see how I split the drawing between two different routines. First, my layer drawing which draws the border, the circle, shadows, etc is handled using raw CALayer drawing. The second block, inside drawRect:, draws the lines forming the “X” inside.
Simply add these files to your project, and create a new DNCloseButton object and add it to your view.
If you find any bugs in this code, please let me know and I’ll update this post. I hope this works out as well for you as it has for me.