UIButton同時設置Title和Image后,默認是圖片在左文字在右,如下圖1,很多情況下我們希望圖片在上圖片在下,如下圖2,只需要簡單的幾行代碼,即可實現。
[_praiseButton setImage:[UIImage imageNamed:@"Share_SendPraise"] forState:UIControlStateNormal];

圖1

(1)因為需要處理多個按鈕,所以將實現代碼封裝為一個方法,把每個UIbutton實例作為參數傳入即可,代碼如下:
- -(void)initButton:(UIButton*)btn{
- btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使圖片和文字水平居中顯示
- [btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height ,-btn.imageView.frame.size.width, 0.0,0.0)];//文字距離上邊框的距離增加imageView的高度,距離左邊框減少imageView的寬度,距離下邊框和右邊框距離不變
- [btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//圖片距離右邊框距離減少圖片的寬度,其它不邊
- }
(2)然后把按鈕傳入
- [self initButton:self.btn1];
- [self initButton:self.btn2];
- [self initButton:self.btn3];
- [self initButton:self.btn4];
- [self initButton:self.btn5];
- [self initButton:self.btn6];
- [self initButton:self.btn7];
