1

Possible Duplicate:
UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

I'm customizing the placement of the image and label of my UIButton but it's only set on the initial state. What the hack, how do I ensure the positioning for all 4 button states?

This is the code I'm using. The poisoning works for the first state but gets reset on the other states.

CGRect imgRect = reviewsButton.imageView.frame;
imgRect.origin.x = 10;
imgRect.origin.y += 4;    
reviewsButton.imageView.frame = imgRect;

CGRect lblrect = reviewsButton.titleLabel.frame;
lblrect.origin.x = 85;
reviewsButton.titleLabel.frame = lblrect;
[reviewsButton setBackgroundColor:[UIColor colorWithRed:0.192 green:0.198 blue:0.206 alpha:0.15]];
Community
  • 1
  • 1
jspooner
  • 10,975
  • 11
  • 58
  • 81

4 Answers4

5

There are UIButton properties which have been made specially for this

@property(nonatomic) UIEdgeInsets contentEdgeInsets
@property(nonatomic) UIEdgeInsets imageEdgeInsets
@property(nonatomic) UIEdgeInsets titleEdgeInsets

Use this property to resize and reposition the effective drawing rectangle for the button image. You can specify a different value for each of the four insets (top, left, bottom, right). A positive value shrinks, or insets, that edge—moving it closer to the center of the button. A negative value expands, or outsets, that edge. Use the UIEdgeInsetsMake function to construct a value for this property. The default value is UIEdgeInsetsZero.

voromax
  • 3,369
  • 2
  • 30
  • 53
0

@jspooner Settings the button frame after you are finished altering the imageview frame and label frame might do the trick.

Rahul Sharma
  • 3,013
  • 1
  • 20
  • 47
0

You should create your image and then apply it to the button states:

UIImage* reviewButtonImage = [UIImage initWithContentsOfFile:/*path*/];
[reviewButton setImage:reviewButtonImage forState:UIControlStateNormal|UIControlStateHighlighted|UIControlStateDisabled|UIControlStateSelected];
gsempe
  • 5,371
  • 2
  • 25
  • 29
  • Thx but the only problem is `UIImage` doesn't have a view or allow you to set the origin. I do like how you placed many states into the forState method. I didn't know you could do that. – jspooner Jun 24 '11 at 04:57
  • Your remark of UIImageView and frame is right. I made a mistake. I deleted my mistake from the answer – gsempe Jun 24 '11 at 05:04
  • @gsempe the multiple states doesn't work – Dejell Jan 29 '13 at 14:08
0

I was never able to get the desired layout to work with UIButton so I created a custom UIView and handled touches there.

jspooner
  • 10,975
  • 11
  • 58
  • 81