#iOS開發(fā)#UIButton文字與圖片的布局

前言

之前對于那種上面是圖片下面是文字的按鈕都是通過一個ImageView、一個Label、一個Button實現(xiàn)的。ImageView和Label在同一層。然后Button覆蓋在他們上面。實現(xiàn)以下效果。

WX20170411-145933.png

其實也一直知道Button有一個屬性可以去控制這個布局。但是一直都懶得搞...今天看到了就寫篇文章分享一下吧。

正文

UIButton中有兩個屬性分別是imageEdgeInsetstitleEdgeInsets用來控制文本與圖片的布局。還有一個contentEdgeInsets用來控制內(nèi)容的布局。
我們先來看看默認(rèn)是什么樣的。默認(rèn)值為UIEdgeInsetsZero

WX20170412-144322.png

    self.button.titleLabel.backgroundColor = [UIColor blueColor];
    self.button.imageEdgeInsets = UIEdgeInsetsZero;
    self.button.titleEdgeInsets = UIEdgeInsetsZero;

<p> </p> <p> </p> <p> </p> <p> </p> <p> </p>

我們先來看看如果修改titleEdgeInsets會怎么樣。

1、Right為正數(shù)

WX20170412-144001.png

整個label往左邊挪了一點點。但是已經(jīng)擠壓了。

    self.button.titleLabel.backgroundColor = [UIColor blueColor];
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);

2、Left為正數(shù)

WX20170412-150709@2x.png

整個label往右邊挪了一點點。同樣被擠壓。

    self.button.titleLabel.backgroundColor = [UIColor blueColor];
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 30, 0, 0);

3、Right為負(fù)數(shù)

WX20170412-145040@2x.png

整個label往左邊挪了一點點。沒有被擠壓。

    self.button.titleLabel.backgroundColor = [UIColor blueColor];
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);

4、Left為負(fù)數(shù)

WX20170412-150248@2x.png

整個label往右邊挪了一點點。沒有被擠壓。

    self.button.titleLabel.backgroundColor = [UIColor blueColor];
    self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -30);

UIEdgeInsets

補充知識??吹竭@里我想大家應(yīng)該都會有一些疑問。那我們就先來看看這個屬性。

    typedef struct UIEdgeInsets {
    CGFloat top, left, bottom, right;  // specify amount to inset (positive) for
 each of the edges. values can be negative to 'outset'
} UIEdgeInsets;

這就是一個結(jié)構(gòu)體。里面包含四個變量。分別是上下左右。代表控件距離四周的距離。我們可以看下圖會有更清晰的認(rèn)識。

1350207-5ea71c94e013a67f.png

所以我們在上面那部分的實驗中。為正數(shù)的值往往都是被被擠壓的。為負(fù)值都會被拉伸。


1、文字與圖片都居中顯示

好了。我們現(xiàn)在去實現(xiàn)讓文字與圖片都居中顯示。

WX20170414-145631@2x.png
   self.button.titleLabel.backgroundColor = [UIColor blueColor];
   self.button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -self.button.titleLabel.intrinsicContentSize.width);
   self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -self.button.imageView.frame.size.width, 0, 0);

大家會看到這里有一個intrinsicContentSize。具體的等下會說。大家可以暫時理解為這是lable的實際大小。這里不能使用size。在iOS8之后titleLabel的size為0。是沒什么意義的。如果想先理解intrinsicContentSize可以看看這篇文章
那么我們現(xiàn)在來思考一下這兩個值是為什么。相當(dāng)于我們就是同時將兩個控件都移動到了中間。所以文字與圖片都居中顯示。

2、文字與圖片都水平居中,圖片在上、文字在下

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

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

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