views:

5867

answers:

3

I have a UIButton and I am trying to set a title and an image on it.

I would like to align the title for a UIButton to the left side and place an image aligned to the right. I am trying to get the look and feel of the button in Timer in Clocks app (the one which says "When Timer Ends").

I fiddled with contentHorizontalAlignment, contentEdgeInsets, titleEdgeInsets and imageEdgeInsets to achieve my goal, but to no avail. The documentation is also quite sparse for the same.

How can I achieve the same?

Also related questions, Timer in Clocks app has two set of Text, one aligned to the left and other aligned right with the image? How can that be done in a UIButton? ( I do not need that functionality though at the moment).

Thanks

+6  A: 

Remember that UIButton inherits from UIView, and so you can add subviews to it just like any other view. In your situation, you would create a button, then add a UILabel on the left side and a UIImage on the right:

// Create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

// Now load the image and create the image view
UIImage *image = [UIImage imageNamed:@"yourImage.png"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(/*frame*/)];
[imageView setImage:image];

// Create the label and set its text
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(/*frame*/)];
[label setText:@"Your title"];

// Put it all together
[button addSubview:label];
[button addSubview:imageView];
Tim
This does not seem to work too well. I have a background image on the button and the label is not visible if I set a background image. If I remove the background image from the button, the label becomes visible? I added the lable to the parent view of UIButton and aligned to sit on top of UIButton and it works then. Any idea why it is behaving this way?
siasl
Usually that kind of behavior presents itself when the background image is added as a subview of the UIButton on top of your custom views. Instead of setting the button's backgroundImage property, think about adding a UIImageView yourself for the background image, then adding the other custom content on top of that image view.
Tim
A: 

I managed to make it work by using a tableview and a single tableviewcell instead.

Apple Clock app also seems to use a tableview in there.

siasl
A: 

Change the imageEdgeInsets property on the UIButton and then just use setImage:forState:

Bill