OBShapedButton: Non-rectangular buttons on the iPhone
UIButton has always been capable of displaying buttons with arbitrary non-rectangular shapes. All you have to do is use PNG images with alpha channels to define the transparent parts of the bounds rectangle.
While a button’s shape may be arbitrary, UIButton always responds to touches within its entire bounds, however. This could cause problems and confusion for the users, especially when multiple non-rectangular buttons are placed close together so that their frames overlap.
OBShapedButton is a replacement for UIButton that solves this issue. Instances of OBShapedButton only respond to touches where the button image is non-transparent. Here’s how to use it:
- Get the code from GitHub.
- Add
OBShapedButton.h,OBShapedButton.m,UIImage+ColorAtPixel.h, andUIImage+ColorAtPixel.mto your Xcode project. - Design your UI in Interface Builder with UIButtons as usual. Set the Button type to Custom and provide transparent PNG images for the different control states as needed.
- In the Identity Inspector in Interface Builder, set the Class of the button to OBShapedButton.
That’s it! Build and run the enclosed demo project to check it out. I am releasing this under the MIT license.
[...] Ole Begemann has also created a custom button class which he talks about here: OBShapedButton: Non-rectangular buttons on the iPhone. [...]
Creating Custom Shaped UIButtons | iPhone and iPad SDK Development Tutorials and Programming Tips
26 Mar 10 at 9:46 pm
Very, very helpful – many thanks!
Iain Barclay
20 May 10 at 1:58 pm
you are the man, dog.
roboris
21 Jun 10 at 1:38 pm
[...] OBShapedButton: Non-rectangular buttons on the iPhone [...]
Irregular Buttons at Under The Bridge
29 Jun 10 at 8:59 am
To get this to work I had to flip the context vertically, otherwise the context you’re using is upside down.
I added this at line 81:
// Flip context
CGContextTranslateCTM(context, 0, height);
CGContextScaleCTM(context, 1.0, -1.0);
—
I think you may have never noticed it because your shapes are diamond shaped so it doesn’t matter if they’re flipped. I was using a PNG of a duck…and was having all sorts of problems!
Let me know if I’m mistaken.
Steven Baughman
16 Jul 10 at 6:42 pm