创建一个 UIButton

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor grayColor];
[button setImage:[UIImage imageNamed:IMAGE] forState:UIControlStateNormal];
[button setTitle:TITLE forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 50);
button.center = self.view.center;
[self.view addSubview:button];

UIButton的默认布局是:title在右,image在左;

%title插图%num

想要修改UIButton的文字位置和图片显示的位置就要借助一个非常重要的属性

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;
表示 上 左 下 右的偏移量;解释下,这四个量的含义:
top : 为正数的时候,是往下偏移,为负数的时候往上偏移;

left : 为正数的时候往右偏移,为负数的时候往左偏移;

bottom : 为正数的时候往上偏移,为负数的时候往下偏移;
right :为正数的时候往左偏移,为负数的时候往右偏移;

实现标题在左 图片在右

CGSize titleSize = button.titleLabel.bounds.size;
CGSize imageSize = button.imageView.bounds.size;
CGFloat interval = 1.0;
button.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
button.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);

%title插图%num
实际图片在上 文字在下

CGSize titleSize = button.titleLabel.bounds.size;
CGSize imageSize = button.imageView.bounds.size;
CGFloat interval = 1.0;
[button setImageEdgeInsets:UIEdgeInsetsMake(0,0, titleSize.height + interval, -(titleSize.width + interval))];
[button setTitleEdgeInsets:UIEdgeInsetsMake(imageSize.height + interval, -(imageSize.width + interval), 0, 0)];

%title插图%num