Ole Begemann: iPhone Development

iPhone Development, Cocoa and Objective-C

OBShapedButton: Non-rectangular buttons on the iPhone

without comments

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, and UIImage+ColorAtPixel.m to 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.

Written by Ole Begemann

October 17th, 2009 at 6:53 pm

Posted in Uncategorized

Leave a Reply