开发者

Position image in UIButton for all states [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

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

开发者_C百科

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 Settings the button frame after you are finished altering the imageview frame and label frame might do the trick.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜