UIButton imageEdgeInsets/titleEdgeInsets簡析

通過設(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的。


imageLeft.png

ButtonImageRight

如果要將image移到右邊來,如下圖,可以看出。image左間距增大labelWidth,image的右間距減少了labelWidth,label的左間距減少了imageWidth,label的右間距增大了imageWidth。

//計(jì)算如下,可以推斷出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

如果我們要設(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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容