UIEdgeInsets是什么
UIEdgeInsets是什么?我們點(diǎn)進(jìn)去看一下:
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; UIEdgeInsets是個(gè)結(jié)構(gòu)體類型。里面有四個(gè)參數(shù),分別是:top, left, bottom, right。這四個(gè)參數(shù)表示距離上邊界、左邊界、下邊界、右邊界的距離。
哪三個(gè)UIEdgeInsets屬性
不知道大家發(fā)現(xiàn)沒(méi)有,UIButton里面有三個(gè)UIEdgeInsets屬性,分別是:
@property(nonatomic) UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero@property(nonatomic) UIEdgeInsets titleEdgeInsets; // default is UIEdgeInsetsZero@property(nonatomic) UIEdgeInsets imageEdgeInsets; // default is UIEdgeInsetsZero
contentEdgeInsets后面有個(gè)UI_APPEARANCE_SELECTOR是什么意思呢?
提示:UI_APPEARANCE_SELECTOR標(biāo)記的屬性都支持通過(guò)外觀代理來(lái)定制。
舉例,設(shè)置UIButton的contentEdgeInsets屬性,可以直接調(diào)用:
[[UIButton appearance] setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
創(chuàng)建UIButton:
UIButton *button = [[UIButton alloc] init];button.frame = CGRectMake(50, 200, 200, 50);[button setTitle:@"我是UIButton" forState:UIControlStateNormal];[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];[button setBackgroundColor:[UIColor orangeColor]];button.titleLabel.textAlignment = NSTextAlignmentLeft;button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;[self.view addSubview:button];
創(chuàng)建一個(gè)button,讓button的title居左,以便觀察:
UIButton的contentEdgeInsets屬性
@property(nonatomic) UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero
contentEdgeInsets里有一個(gè)content應(yīng)該指的就是UIButton的title。
參數(shù)含義:
上面我們講了UIEdgeInsets是個(gè)結(jié)構(gòu)體類型。里面有四個(gè)參數(shù),分別是:top, left, bottom, right。這四個(gè)參數(shù)表示距離上邊界、左邊界、下邊界、右邊界的距離。
這四個(gè)參數(shù)的值可以為正值,也可以為負(fù)值。拿left舉例:
left = 10; //代表以當(dāng)前位置為基準(zhǔn),向右移動(dòng)10個(gè)像素left = -10; //代表以當(dāng)前位置為基準(zhǔn),向左移動(dòng)10個(gè)像素
向右移動(dòng)20個(gè)像素
button.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
向右移動(dòng)20個(gè)像素,left = 20,就可以了。
向左移動(dòng)20個(gè)像素
button.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
UIButton的titleEdgeInsets屬性
titleEdgeInsets和contentEdgeInsets的作用差不多。我們及設(shè)置contentEdgeInsets,又設(shè)置titleEdgeInsets,會(huì)怎樣呢?
button.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);button.contentEdgeInsets = UIEdgeInsetsMake(0, 20 , 0, 0);
看一下效果:
UIButton的imageEdgeInsets屬性
創(chuàng)建一個(gè)帶照片的button:
UIButton *button = [[UIButton alloc] init];button.frame = CGRectMake(50, 200, 200, 200);[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];[button setBackgroundColor:[UIColor orangeColor]];[button setImage:[UIImage imageNamed:@"test"] forState:UIControlStateNormal];[self.view addSubview:button];
運(yùn)行一下:
向右移動(dòng)50個(gè)像素
button.imageEdgeInsets = UIEdgeInsetsMake(0, 50, 0, 0);
看看效果:
向左移動(dòng)50個(gè)像素
button.imageEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0);
看看效果:
大家可以自行設(shè)置其他三個(gè)參數(shù)看看效果是怎樣的,自己動(dòng)手便于理解。


























