通過設(shè)置imageEdgeInsets可以設(shè)置button圖標(biāo)的上下左右間距,同樣,titleEdgeInsets可以改變title的四周的間距。之前還不知道這2個(gè)屬性,自己還專門寫了個(gè)button來動(dòng)態(tài)調(diào)整間距,o(╯□╰)o。
默認(rèn)的,image和title之間的間距為0,二者水平垂直方向整體居中,imageEdgeInsets和titleEdgeInsets均為
UIEdgeInsetsZero。
left > 0,左邊距增大,右移,< 0,左移。top > 0,上邊距增大,下移,< 0,上移。right > 0,右邊距增大,左移,< 0,右移。bottom > 0,下邊距增大,上移,< 0, 下移。
這樣,我們就可以通過控制inset來調(diào)整方位了。
首先我們來定義一個(gè)枚舉,定義image的位置。
//圖片位置
enum ButtonImagePosition: Int {
case ButtonImageLeft = 0
case ButtonImageRight
case ButtonImageTop
case ButtonImageBottom
}
ButtonImageLeft
默認(rèn)是ButtonImageLeft的。

ButtonImageRight
如果要將image移到右邊來,如下圖,可以看出。image左間距增大labelWidth,image的右間距減少了labelWidth,label的左間距減少了imageWidth,label的右間距增大了imageWidth。
//計(jì)算如下,可以推斷出right = -left,同理bottom = -top
imageLeft = labelWidth
imageRight = -labelWidth
labelLeft = -imageWidth
labelRight = imageWidth

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。

ButtonImageBottom
將image移到下方。可以參照ButtonImageTop的自行算出。

添加space
如果我們要設(shè)置image和title之間的間距呢,也很簡單。計(jì)算時(shí)+/-space*0.5就可以了。
如space=5,
ButtonImageRight:imageLeft = labelWidth + space / 2
ButtonImageTop:imageTop = -labelHeight / 2 - space / 2
我寫了個(gè)button的extension,代碼在https://github.com/silan-liu/buttonEdgeInset.git