I need to generate a custom button through code, this is how i am currently doing it.
-(void) initialiseButtons
{
int ypos = playerImage.frame.origin.y
An easy way to do this, is to override a UIView. In the view you add a UIButton as Subview. This way you have a reusable class without the need to re-implement button behaviour.
You can style your button the way you want in the initWithFrame method of your UIView derived class. If you use this class as target for your button events, you can implement special behaviour easily, like showing the image.
For the two pieces of text, you create two labels and add them as subviews to the button.
You should not (I'd almost say you can't) subclass UIButton
, as it turns out to be a class cluster, and it would be impractical (read: impossible) to derive from that.
So your two options are:
1) Use standard UIButton
of custom type, add the elements you want to show (i.e. UILabel
) and hook up actions for touch down and touch up and react accordingly (change the views, trigger actions etc.)
2) Use a custom UIView
, implement drawRect:
to draw how you like it or use custom views as subviews as in 1). Then use the touchesBegan:
, touchesEnded:
etc. messages to react accordingly (or UIGestureRecognizer
if you can live with 3.2+ compatibility).
You might build a factory to build those buttons if they all are very similar, so that your code becomes clean and non-repetive.
Edit as per iOS 6: Apple now mentions subclassing in the UIButton docs, so while still not very well defined, it seems quite safe now to do so.
Personally, I would subclass UIButton. Despite all the talk that you can't subclass UIButton, Apple even talks about subclassing UIButton in the UIButton documentation.
In the subclass I would create a UIView with the two labels (or images or whatever) and add them as subviews to the button (be sure to set interactive for the text and view as FALSE).
What is awesome about this is that it leverages the UIButton code and keeps you from reinventing the wheel.