UIButton的titleEdgeInsets属性和p_w_picpathEdgeInsets属性实现图片文字按要求排列

button可以设置 titleEdgeInsets属性和 p_w_picpathEdgeInsets属性来调整其p_w_picpath和label相对位置,具体参考http://stackoverflow.com/questions/4564621/aligning-text-and-p_w_picpath-on-uibutton-with-p_w_picpathedgeinsets-and-titleedgeinsets/5358259#5358259的第二个答案,关键是这个:

 

这里说说我自己的理解,理解有误的地方,大家可以讨论

 

前提:这是在button的frame足够显示p_w_picpath和label内容的情况下,如果frame不够,图片或者文字会被压缩(demo的button是xib上画的,所以大小刚刚好)

 

前置知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的,

如果只有title,那它上下左右都是相对于button的,p_w_picpath也是一样;

如果同时有p_w_picpath和label,那这时候p_w_picpath的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于p_w_picpath的。

 

我写了个demo来说明怎么设置这两个属性以达到自己想要的效果:https://github.com/Phelthas/Demo_ButtonImageTitleEdgeInsets

看效果图来说明一下:

其中,右边的是给对应的左边的button及button.p_w_picpathView, button.titleLabel加上边框的效果

 

默认情况下,button的p_w_picpath和label是紧贴着居中的,

那如果想要p_w_picpath在右边,label在左边应该怎么办呢?

答案就是:

self.oneButton.p_w_picpathEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);

self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -p_w_picpathWith, 0, p_w_picpathWith);

来解释一下为什么:

其实就是这一句:This property is used only for positioning the p_w_picpath during layout

其实titleEdgeInsets属性和 p_w_picpathEdgeInsets属性只是在画这个button出来的时候用来调整p_w_picpath和label位置的属性,并不影响button本身的大小(这个看第三排的图比较明显),

它们只是p_w_picpath和button相较于原来位置的偏移量,那什么是原来的位置呢?就是这个没有设置edgeInset时候的位置了。

 

如要要p_w_picpath在右边,label在左边,那p_w_picpath的左边相对于button的左边右移了labelWidth的距离,p_w_picpath的右边相对于label的左边右移了labelWidth的距离

所以,self.oneButton.p_w_picpathEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);为什么是负值呢?因为这是contentInset,是偏移量,不是距离

同样的,label的右边相对于button的右边左移了p_w_picpathWith的距离,label的左边相对于p_w_picpath的右边左移了p_w_picpathWith的距离

所以self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -p_w_picpathWith, 0, p_w_picpathWith);

这样就完成p_w_picpath在右边,label在左边的效果了。

 

 

第三排,p_w_picpath在上,label在下

同样的第三排调整前的还是第一排的样子,

跟第一排比起来,p_w_picpath的中心位置向右移动了 CGFloat p_w_picpathOffsetX = (p_w_picpathWith + labelWidth) / 2 - p_w_picpathWith / 2;

上向上移动了 CGFloat p_w_picpathOffsetY = p_w_picpathHeight / 2;

所以self.twoButton.p_w_picpathEdgeInsets = UIEdgeInsetsMake(-p_w_picpathOffsetY, p_w_picpathOffsetX, p_w_picpathOffsetY, -p_w_picpathOffsetX);

label的中心位置像左移动了CGFloat labelOffsetX = (p_w_picpathWith + labelWidth / 2) - (p_w_picpathWith + labelWidth) / 2;

向下移动了CGFloat labelOffsetY = labelHeight / 2;

所以self.twoButton.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX);

然后就大功告成了,现在已经完美实现一个button内p_w_picpath在上,label在下,切居中了