Position image in UIButton for all states

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]];

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.


@jspooner完成修改imageview框架和标签框架后,设置按钮框架可能会起到一定作用。


您应该创建您的图像,然后将其应用于按钮状态:

UIImage* reviewButtonImage = [UIImage initWithContentsOfFile:/*path*/];
[reviewButton setImage:reviewButtonImage forState:UIControlStateNormal|UIControlStateHighlighted|UIControlStateDisabled|UIControlStateSelected];
链接地址: http://www.djcxy.com/p/28246.html

上一篇: 图像不在UIButton的中心对齐

下一篇: 在UIButton中为所有状态定位图像