【转】iOS UIButton(UIEdgeInsets)

来源:互联网 发布:软件前景 编辑:程序博客网 时间:2024/05/17 12:06
转:http://www.knowsky.com/883202.html


button可以设置 titleEdgeInsets属性和imageEdgeInsets属性来调整其image和label相对位置,具体参考http://stackoverflow.com/questions/4564621/aligning-text-and-image-on-uibutton-with-imageedgeinsets-and-titleedgeinsets/5358259的第二个答案,关键是这个:
 
这里说说我自己的理解,理解有误的地方,大家可以讨论
 
前提:这是在button的frame足够显示image和label内容的情况下,如果frame不够,图片或者文字会被压缩(demo的button是xib上画的,所以大小刚刚好)
 
前置知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的,
如果只有title,那它上下左右都是相对于button的,image也是一样;
如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。
 
我写了个demo来说明怎么设置这两个属性以达到自己想要的效果:https://github.com/Phelthas/Demo_ButtonImageTitleEdgeInsets
看效果图来说明一下:
其中,右边的是给对应的左边的button及button.imageView,button.titleLabel加上边框的效果
 
默认情况下,button的image和label是紧贴着居中的,
那如果想要image在右边,label在左边应该怎么办呢?
答案就是:
self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0,-labelWidth);
self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0,imageWith);
来解释一下为什么:
其实就是这一句:This PRopertyis used only for positioning the image during layout
其实titleEdgeInsets属性和imageEdgeInsets属性只是在画这个button出来的时候用来调整image和label位置的属性,并不影响button本身的大小(这个看第三排的图比较明显),
它们只是image和button相较于原来位置的偏移量,那什么是原来的位置呢?就是这个没有设置edgeInset时候的位置了。
 
如要要image在右边,label在左边,那image的左边相对于button的左边右移了labelWidth的距离,image的右边相对于label的左边右移了labelWidth的距离
所以,self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth,0, -labelWidth);为什么是负值呢?因为这是contentInset,是偏移量,不是距离
同样的,label的右边相对于button的右边左移了imageWith的距离,label的左边相对于image的右边左移了imageWith的距离
所以self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith,0, imageWith);
这样就完成image在右边,label在左边的效果了。
 
 
第三排,image在上,label在下
同样的第三排调整前的还是第一排的样子,
跟第一排比起来,image的中心位置向右移动了 CGFloat imageOffsetX = (imageWith +labelWidth) / 2 - imageWith / 2;
上向上移动了CGFloat imageOffsetY = imageHeight / 2;
所以self.twoButton.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY,imageOffsetX, imageOffsetY, -imageOffsetX);
label的中心位置像左移动了CGFloatlabelOffsetX = (imageWith + labelWidth / 2) - (imageWith +labelWidth) / 2;
向下移动了CGFloat labelOffsetY = labelHeight / 2;
所以self.twoButton.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY,-labelOffsetX, -labelOffsetY, labelOffsetX);
然后就大功告成了,现在已经完美实现一个button内image在上,label在下,切居中了
0 0