在使用UIButton的時候正常設(shè)置文字和圖片之后 ,圖片和文字的位置默認的是并排水平居中button

6C6A19DD-F144-42B3-8773-FDA3F5FE44AC.png
這時需要使用
UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)
button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
button.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
四個參數(shù)分別代表 距離button上,左,下,右的距離
我們調(diào)整下圖片和文字的位置
leftWith 暫時表示屏幕寬度
24 是 圖片的寬度
button.imageEdgeInsets = UIEdgeInsetsMake(-3, (leftWith/3-24)/2, 15, 0);
button.titleEdgeInsets = UIEdgeInsetsMake(27, -(leftWith/3-24)/2, 0, 0);
設(shè)置之后看下效果

C74CE0C6-973B-4601-8A96-33DAF857D446.png
另外有的時候button上面有文字 我們又想讓文字在某一處折行
我們設(shè)置
button.titleLabel.numberOfLines = 2;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
然后在你需要折行的地方加上'\n'
[button setTitle:@"藍瘦\n香菇" forState:UIControlStateNormal];
我的實際項目中例子:
UIButton *addShoppingCart =[FactoryUI createButtonWithFrame:CGRectMake(leftWith, 0, rightWith*2/5, 49) title:@"¥66.00\n加入購物車" titleColor:[UIColor whiteColor] backgroundColor:RGB(255, 128, 147, 1) type:UIButtonTypeCustom target:self selector:@selector(addShopCart)];
addShoppingCart.titleLabel.font = FONT(15);//title字體大小
addShoppingCart.titleLabel.font = [UIFont boldSystemFontOfSize:15];
addShoppingCart.titleLabel.numberOfLines = 2;
addShoppingCart.titleLabel.textAlignment = NSTextAlignmentCenter
效果:

586153F3-5EAB-492D-88C5-2B30BDD16047.png