UIEdgeInsets实际就是一个结构体,UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
上面的结构体,我理解就是距离上、左、下、右的偏移距离,比如上,正数就是距离上面增加偏移量,负数就是减少偏移量
居中之后相当于抵消了原来的偏移量,还要再增加一倍的偏移量,所以最后是两倍的偏移量,还可以增加间距
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"pullup"] forState:UIControlStateNormal];
[btn setTitle:@"更多sdfac打发的发" forState:UIControlStateNormal];
btn.backgroundColor = [UIColor lightGrayColor];
btn.frame = CGRectMake(100, 300, 100, 30);
[self.view addSubview:btn];
// 还可增设间距
CGFloat spacing = 3.0;
// 图片右移
CGSize imageSize = btn.imageView.frame.size;
btn.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width * 2 - spacing, 0.0, 0.0);
// 文字左移
CGSize titleSize = btn.titleLabel.frame.size;
btn.imageEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, - titleSize.width * 2 - spacing);
重新设置titleLabel的text也要重新执行后面两句,当文本太长的时候显示有问题,需要截取