UIButton中的titleEdgeInsets和imageEdgeInsets可以管理button中title和image的布局。利用这两个属性就可以轻松的设置一个图片一个文本这样的布局。
但是先要对着两个属性了解清楚
UIButton *btnCeShi = [[UIButton alloc]initWithFrame:CGRectMake(20, 30, 80, 80)];
[self.view addSubview:btnCeShi];
btnCeShi.backgroundColor = [UIColor redColor];
[btnCeShi setTitle:@"测试" forState:UIControlStateNormal];
[btnCeShi setImage:[UIImage imageNamed:@"select"] forState:UIControlStateNormal];
这是一个基本的button,默认情况下,图片在左,文字在右,垂直居中显示,如上图。
只设置image或title其中一项时,默认是正常居中显示的,但我们同时设置image和title时,则会出现上图的显示,这是为什么呢?那就是当我们同时添加image和title时,image默认会向左偏移button的titleLabel的宽度,而title会向右偏移image的宽度,既然明白了原理,我们就可以设置偏移量来达到我们想要的任何效果。
默认情况下
button.titleEdgeInsets = UIEdgeInsetsZero;
button.imageEdgeInsets = UIEdgeInsetsZero;
现在我们就可以任意的修改button的布局
1. 设置图片和文字都是居中的布局
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width, 0, 0);
// button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.titleLabel.frame.size.width);
// 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可
button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.titleLabel.intrinsicContentSize.width);
2. 设置图片在上,文字在下,水平居中显示
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width, -button.imageView.frame.size.height, 0);
// button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.frame.size.height, 0, 0, -button.titleLabel.frame.size.width);
// 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可
button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.intrinsicContentSize.height, 0, 0, -button.titleLabel.intrinsicContentSize.width);
如果觉得图片和文字离的太近了,稍微分开一点:
CGFloat offset = 40.0f;
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width, -button.imageView.frame.size.height-offset/2, 0);
// button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.frame.size.height-offset/2, 0, 0, -button.titleLabel.frame.size.width);
// 由于iOS8中titleLabel的size为0,用上面这样设置有问题,修改一下即可
button.imageEdgeInsets = UIEdgeInsetsMake(-button.titleLabel.intrinsicContentSize.height-offset/2, 0, 0, -button.titleLabel.intrinsicContentSize.width);
2. 设置文字左对齐,图片右对齐
button.titleEdgeInsets = UIEdgeInsetsMake(0, -button.imageView.frame.size.width - button.frame.size.width + button.titleLabel.intrinsicContentSize.width, 0, 0);
button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -button.titleLabel.frame.size.width - button.frame.size.width + button.imageView.frame.size.width);