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

其實也一直知道Button有一個屬性可以去控制這個布局。但是一直都懶得搞...今天看到了就寫篇文章分享一下吧。
正文
UIButton中有兩個屬性分別是imageEdgeInsets與titleEdgeInsets用來控制文本與圖片的布局。還有一個contentEdgeInsets用來控制內(nèi)容的布局。
我們先來看看默認(rèn)是什么樣的。默認(rèn)值為UIEdgeInsetsZero

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ù)

整個label往左邊挪了一點點。但是已經(jīng)擠壓了。
self.button.titleLabel.backgroundColor = [UIColor blueColor];
self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
2、Left為正數(shù)

整個label往右邊挪了一點點。同樣被擠壓。
self.button.titleLabel.backgroundColor = [UIColor blueColor];
self.button.titleEdgeInsets = UIEdgeInsetsMake(0, 30, 0, 0);
3、Right為負(fù)數(shù)

整個label往左邊挪了一點點。沒有被擠壓。
self.button.titleLabel.backgroundColor = [UIColor blueColor];
self.button.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
4、Left為負(fù)數(shù)

整個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)識。

所以我們在上面那部分的實驗中。為正數(shù)的值往往都是被被擠壓的。為負(fù)值都會被拉伸。
1、文字與圖片都居中顯示
好了。我們現(xiàn)在去實現(xiàn)讓文字與圖片都居中顯示。

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)于我們就是同時將兩個控件都移動到了中間。所以文字與圖片都居中顯示。