UIButton的图文混排主要取决于两个属性:imageEdgeInsets和titleEdgeInsets,默认情况下它们都等于UIEdgeInsetsMake(0, 0, 0, 0),通过改变这两个属性,来控制按钮中图片和文字的位置。下面通过四个需求,说一下这两个属性应该怎么设置。
首先创建一个按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 100, 150, 100);
btn.titleLabel.font = [UIFont systemFontOfSize:14];
btn.backgroundColor = [UIColor lightGrayColor];
btn.titleLabel.backgroundColor = [UIColor purpleColor];
btn.imageView.backgroundColor = [UIColor greenColor];
[btn setTitle:@"购物车" forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"shopcar"] forState:0];
[self.view addSubview:btn];
//间距
CGFloat space = 20;
//得到图片和标题的宽高
CGFloat imageWidth = CGRectGetWidth(btn.imageView.frame);
CGFloat imageHeight = CGRectGetHeight(btn.imageView.frame);
CGFloat titleWidth = CGRectGetWidth(btn.titleLabel.frame);
CGFloat titleHeight = CGRectGetHeight(btn.titleLabel.frame);
上面的按钮没有设置imageEdgeInsets和titleEdgeInsets属性,默认它们都等于UIEdgeInsetsMake(0, 0, 0, 0),此时的效果是这样:
需求1:让图片和标题的左右间距为space。
本质上:
图片向左移动space/2
标题向右移动space/2,也即是:
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0 - space / 2, 0, 0 + space / 2);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0 + space / 2, 0, 0 - space / 2);
效果如下:
需求2:让图片和标题对换位置。
本质上:
图片右移titleWidth
标题左移imageWidth,也即是:
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0 + titleWidth, 0, 0 - titleWidth);
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0 - imageWidth, 0, 0 + imageWidth);
效果如下:
需求3:让图片和标题对换位置,左右间距为space。
本质上:
图片右移(titleWidth+space/2)
标题左移(imageWidth+space/2),也即是:
btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0 + (titleWidth + space / 2), 0, 0 - (titleWidth + space / 2));
btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0 - (imageWidth + space / 2), 0, 0 + (imageWidth + space / 2));
效果如下:
需求4:让图片在上,标题在下,上下间距为space。
本质上:
图片右移(imageWidth + titleWidth) / 4.0
标题左移(imageWidth + titleWidth) / 4.0
图片上移(titleHeight / 2.0 + space / 2)
标题下移(imageHeight / 2.0 + space / 2),也即是:
btn.imageEdgeInsets = UIEdgeInsetsMake(0 - (titleHeight / 2.0 + space / 2), 0 + (imageWidth + titleWidth) / 4.0, 0 + (titleHeight / 2.0 + space / 2), 0 - (imageWidth + titleWidth) / 4.0);
btn.titleEdgeInsets = UIEdgeInsetsMake(0 + (imageHeight / 2.0 + space / 2), 0 - (imageWidth + titleWidth) / 4.0, 0 - (imageHeight / 2.0 + space / 2), 0 + (imageWidth + titleWidth) / 4.0);
效果如下:
总结:
UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right);
无论图片还是标题:
左移:left = 0 - 左移距离;right = - left
右移:left = 0 + 右移距离;right = - left
上移:top = 0 - 上移距离;bottom = - top
下移:top = 0 + 下移距离;bottom = - top