我們先看一下蘋果官方對UIEdgeInsets說明:
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;
- 官方:specify amount to inset (positive) for each of the edges. values can be negative to 'outset' .
- 解釋:對每條邊向內(nèi)方向的偏移量悦施,可以為正值(向內(nèi)偏移)也可以為負(fù)值(向外偏移)并扇。
基本使用:
xxx.edgeInsets = UIEdgeInsetsMake(.0, .0, .0, .0);
//例如我們設(shè)置UICollectionView的edgeInset會使collectionView產(chǎn)生內(nèi)偏移
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(20.0, .0, .0, .0);
引入正題:
然而,UIButton的內(nèi)偏移量與其他控件有些區(qū)別抡诞,
因為UIButton內(nèi)部默認(rèn)有兩個子控件:UILabel和UIImageView
所以UIButton在內(nèi)偏移量的計算上會有差異穷蛹。
為什么?先賣個關(guān)子昼汗,下文解釋肴熏。
UIButtonEdgeInsets:
需求:通過修改edgeInsets,改變Button內(nèi)部的ImageView和titleLabel的相對位置顷窒。
小編做了一個demo蛙吏,效果如下圖:
思路:通過修改button的兩個屬性:titleEdageInsets和imageEdgeInsets,從而達(dá)到最終的具體需求鞋吉。這里列出了三個比較常見的需求:
- image左 title右
- image右 title左
- image上 title下
場景一:左圖右字
button.titleEdgeInsets = UIEdgeInsetsMake(0, 10.0, 0, 0);
語法解釋:設(shè)置了title的左邊線的內(nèi)偏移量為10.0鸦做,
但經(jīng)測試,
注意:實際上title和Image直接只有5.0的距離
注意:實際上title和Image直接只有5.0的距離
注意:實際上title和Image直接只有5.0的距離
圖解如下:
在這種場景下:
- title的 上邊線坯辩、右邊線馁龟、下邊線 內(nèi)偏移 是相對于contentView的
- image的 上邊線、左邊線漆魔、下邊線 內(nèi)偏移 是相對于contentView的
- title的 左邊線 內(nèi)偏移 相對于image
- image的 右邊線 內(nèi)偏移 相對于title
場景二:左字右圖
button.titleEdgeInsets = UIEdgeInsetsMake(.0, - button.imageView.bounds.size.width - 10.0, .0, button.imageView.bounds.size.width);
button.imageEdgeInsets = UIEdgeInsetsMake(.0, button.titleLabel.bounds.size.width, .0, - button.titleLabel.bounds.size.width);
語法解釋:
- title的 左邊線 內(nèi)偏移 - (imageView.width +10)<=> 等價于 title的左邊線 向 內(nèi)偏移的反方向 移動 (image.width +10)
- title的 右邊線 內(nèi)偏移 imageView.width <=> 等價于 title的右邊線 向 內(nèi)偏移的正方向 移動 imageView.width
- image的 左邊線 內(nèi)偏移 titleLabel.width <=> 等價于 image的左邊線 向 內(nèi)偏移的正方向 移動 titleLabel.width
- image的 右邊線 內(nèi)偏移 - titleLabel.width <=> 等價于 title的左邊線 向 內(nèi)偏移的反方向 移動 titleLabel.width
是不是有點繞人?哈哈却音,不要慌改抡,請看圖解
場景三:上圖下字
button.titleEdgeInsets = UIEdgeInsetsMake(button.imageView.frame.size.height + 10.0, - button.imageView.bounds.size.width, .0, .0);
button.imageEdgeInsets = UIEdgeInsetsMake(.0, button.titleLabel.bounds.size.width / 2, button.titleLabel.frame.size.height + 10.0, - button.titleLabel.bounds.size.width / 2);
語法解釋:
- title的 上邊線 內(nèi)偏移 (imageView.height +10)<=> 等價于 title的上邊線 向 內(nèi)偏移的正方向 移動 (image.height +10)
- title的 左邊線 內(nèi)偏移 - imageView.width <=> 等價于 title的左邊線 向 內(nèi)偏移的反方向 移動 image.width
- image的 左邊線 內(nèi)偏移 titleLabel.width * 0.5 <=> 等價于 image的左邊線 向 內(nèi)偏移的正方向 移動 titleLabel.width 的一半
- image的 下邊線 內(nèi)偏移 titleLabel.height + 10 <=> 等價于 image的下邊線 向 內(nèi)偏移的正方向 移動 titleLabel.height + 10
- image的 右邊線 內(nèi)偏移 - titleLabel.width * 0.5 <=> 等價于 image的右邊線 向 內(nèi)偏移的反方向 移動 titleLabel.width 的一半
請看圖解: