Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton title and image alignment query

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).

like image 871
siasl Avatar asked Jul 12 '09 14:07

siasl


4 Answers

Here is the code I use for that:

//Right-align the button image
CGSize size = [[myButton titleForState:UIControlStateNormal] sizeWithFont:myButton.titleLabel.font];
[myButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -size.width)];
[myButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, myButton.imageView.image.size.width + 5)];
like image 118
ingham Avatar answered Nov 20 '22 04:11

ingham


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

like image 35
Bill Avatar answered Nov 20 '22 03:11

Bill


The following code works:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonRect;
[button setTitle:@"A title" forState:UIControlStateNormal];
[button setImage:buttonImage forState:UIControlStateNormal];
button.imageEdgeInsets = UIEdgeInsetsMake(0.0, WIDTH(button.titleLabel) + 10.0, 0.0, 0.0);
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
like image 14
yaris Avatar answered Nov 20 '22 02:11

yaris


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];
like image 9
Tim Avatar answered Nov 20 '22 04:11

Tim