UIButton imageEdgeInsets/titleEdgeInsets简析

1,027 阅读1分钟

通过设置 imageEdgeInsets 可以设置 button 图标的上下左右间距,同样,titleEdgeInsets 可以改变 title 的四周的间距。之前还不知道这 2 个属性,自己还专门写了个 button 来动态调整间距,o(╯□╰)o。

默认的,image 和 title 之间的间距为 0,二者水平垂直方向整体居中,imageEdgeInsets 和 titleEdgeInsets 均为
UIEdgeInsetsZero。

left > 0,左边距增大,右移,<0,左移。top> 0,上边距增大,下移,< 0,上移。right > 0,右边距增大,左移,< 0,右移。bottom > 0,下边距增大,上移,< 0, 下移。

这样,我们就可以通过控制 inset 来调整方位了。

首先我们来定义一个枚举,定义 image 的位置。

//图片位置
enum ButtonImagePosition: Int {
    case ButtonImageLeft = 0
    case ButtonImageRight
    case ButtonImageTop
    case ButtonImageBottom
}

ButtonImageLeft

默认是 ButtonImageLeft 的。

imageLeft.png

ButtonImageRight

如果要将 image 移到右边来,如下图,可以看出。image 左间距增大 labelWidth,image 的右间距减少了 labelWidth,label 的左间距减少了 imageWidth,label 的右间距增大了 imageWidth。

// 计算如下,可以推断出 right = -left,同理 bottom = -top
imageLeft = labelWidth
imageRight = -labelWidth

labelLeft = -imageWidth
labelRight = imageWidth

imageRight.png

ButtonImageTop

将 image 移到上方。

newImageY = (buttonHeight - (labelHeight + imageHeight)) / 2

// new
imageLeft = (buttonWidth - imageWidth) / 2 - (buttonWidth - (labelWidth + imageWidth) / 2) => (labelWidth / 2)

// newImageY - oldImageY
imageTop = newImageY - (buttonHeight - imageHeight) / 2 => (-labelHeight / 2)

labelLeft = (buttonWidth - (labelWidth + imageWidth) / 2) - (buttonWidth - labelWidth) / 2 => (-imageWidth / 2)

labelTop = newImageY + imageHeight - (buttonHeight - labelHeight) / 2 => (imageHeight / 2)

同理可以算出 label 的 left,top。

imageTop.png

ButtonImageBottom

将 image 移到下方。可以参照 ButtonImageTop 的自行算出。

imageBottom.png

添加 space

如果我们要设置 image 和 title 之间的间距呢,也很简单。计算时 +/-space*0.5 就可以了。
如 space=5,

ButtonImageRight:imageLeft = labelWidth + space / 2
ButtonImageTop:imageTop = -labelHeight / 2 - space / 2

我写了个 button 的 extension,代码在 github.com/silan-liu/b…