在UIButton中有label和imageView两个控件,只有我们设置好了他们与按钮本省之间的间距,那么UIButton就能够显示出我们希望的效果。
typedefstruct UIEdgeInsets {
CGFloat top, left, bottom, right; // specify amount to inset (positive) for each of the edges. values can be negative to 'outset'
} UIEdgeInsets; //UIEdgeInsets是一个结构体,结构体中的成员代表的是距离上边界,左边界,下边界,右边界之间的距离
如果我们需要实现一种这样的效果,应该如何设置titleEdgetInsets和imageEdgetInsets的值呢?
在UIButton中默认的是image在前label在后,而且两者之间没有任何的间隙,titleEdgeInsets和imageEdgeInsets默认为0; 在我们设置EdgeInsets的值时,我们应该考虑的是把label和imageView当作一个整体来考虑。
如上图的要求:label离按钮的左边为34,imageView离按钮的右边为34
代码:
#define BUTTON_WIDTH self.view.frame.size.width
#define BUTTON_HEIGHT 44
#define IMAGE_WIDTH 8
#define GAP 17
//创建一个Button
-(UIButton *) createDetailButton:(CGRect )rect title :(NSString *)title image:(UIImage *)image titleColor:(UIColor *)color selectedColor:(UIColor *)selectedColor titleFont:(UIFont *)font titleEdgeInset:(UIEdgeInsets) titleEdge imageEdgeInset:(UIEdgeInsets)imageEdge withTag:(int) tag
{
UIButton *button = [[UIButtonalloc]initWithFrame:rect];
[button setTitle:titleforState:UIControlStateNormal];
[button setTitleColor:colorforState:UIControlStateNormal];
[button.titleLabelsetFont:font];
[button setImage:imageforState:UIControlStateNormal];
button.imageEdgeInsets = imageEdge;
button.titleEdgeInsets = titleEdge;
[button setBackgroundImage:[UIImageimageWithColor:selectedColor]forState:UIControlStateHighlighted];
[button addTarget:selfaction:@selector(detailButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
button.tag = tag;
return button;
}
-(void) buttonWithTitleAndImage
{
CGSize size = [@"入账明细"sizeWithFont:SEVENTEENFONT]; //得到label的长和宽
UIButton *ruzhangButton = [selfcreateDetailButton:CGRectMake(0,0.5,self.view.frame.size.width,44)title:@"入账明细"image:[UIImage imageNamed:(@"icon_arrow")] titleColor:[UIColor colorWithRed:0 green:0 blue 0 alpha:1.0] selectedColor:[UIColor colorWithRed:217 green:217 blue 217 alpha:1.0]titleFont:[UIFont SystemFontOfSize:17.0] titleEdgeInset:UIEdgeInsetsZeroimageEdgeInset:UIEdgeInsetsZerowithTag:1992];
UIEdgeInsets titleEdgeInset =UIEdgeInsetsMake((BUTTON_HEIGHT - size.height)/2 ,GAP -IMAGE_WIDTH , (BUTTON_HEIGHT - size.height)/2,BUTTON_WIDTH -GAP - size.width);
//titleEdgeInsets的top值为button的高度减去label的高度 然后除以2 ,bottom的值也是一样的,接着看left 和 right的值,(再次强调一句设置间距的时候一定要把label和image当作一个整体来考虑,images在前,label在后,而且两者之间没有间隙)
//图中黑色的是我们假象存在的,在设置titleEdgeInsets时,我们可以假设在Label的前面还有一个image,我们就可以得出label距离按钮右边的距离为:BUTTON_WIETH - GAP - size.width,label距离按钮左边的距离为GAP - IMAGE_WIDTH,这样理解我们就可以很快的写出以上那句设置tilteEdgeInsets的代码。
UIEdgeInsets imageEdgeInset = UIEdgeInsetsMake(15.5,BUTTON_WIDTH -GAP - IMAGE_WIDTH,15.5,GAP - size.width);
//设置imageEdgeInsets的时候也是把image和label当作一个整体,如图中黑色的label所示,imageView的左边和button的左边的距离为:button的宽度减去imageView的宽度, 再减去间隙(即:BUTTON_WIDTH - IMAGE_WIDTH - GAP), imageView的右边与label右边的距离为:间隙 减去 label的宽度(即:GAP - size.width),以此可以得出imageEdgeInsets的值。
ruzhangButton.titleEdgeInsets = titleEdgeInset;
ruzhangButton.imageEdgeInsets = imageEdgeInset;
}