UIButton 雖然可以同時設定 title 與 image,但系統只會把圖片置中、文字放在下方,位置完全無法直接指定。要達到「圖在右、文字靠左填滿」這種設計稿常見的排版,必須覆寫兩個方法。
目標效果:

UIButton 內部會呼叫 titleRectForContentRect: 與 imageRectForContentRect: 來決定子元素的 frame。只要覆寫這兩個方法,就能完全掌控排版。
#import "yxpButton.h"
@implementation yxpButton
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 可依需求自由調整
self.titleLabel.textAlignment = NSTextAlignmentRight;
self.titleLabel.font = [UIFont systemFontOfSize:14.0];
self.imageView.contentMode = UIViewContentModeLeft;
}
return self;
}
// 依 button 的 contentRect 決定 title 的位置
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
CGFloat titleW = contentRect.size.width - 30; // 右側留 30pt 給圖片
CGFloat titleH = contentRect.size.height;
return CGRectMake(0, 0, titleW, titleH);
}
// 依 button 的 contentRect 決定 imageView 的位置
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
CGFloat imageW = 25;
CGFloat imageH = 25;
CGFloat imageX = contentRect.size.width - 26;
CGFloat imageY = 2.5;
return CGRectMake(imageX, imageY, imageW, imageH);
}
@end
yxpButton *selectAreaButton =
[[yxpButton alloc] initWithFrame:CGRectMake(200, 5, 100, 30)];
[selectAreaButton setTitle:@"圖文混排" forState:UIControlStateNormal];
[selectAreaButton setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
[selectAreaButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[navigationBgView addSubview:selectAreaButton];
這兩個方法的參數 contentRect,是扣掉 contentEdgeInsets 之後的可用區域。你回傳什麼,系統就把 title 或 image 擺在那裡。範例中的數字(30、26、2.5)是硬編碼,實務上建議改用比例計算,例如:
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
CGFloat imageW = 16;
return CGRectMake(contentRect.size.width - imageW - 4,
(contentRect.size.height - imageW) / 2.0,
imageW, imageW);
}
這樣換不同高度的按鈕時,圖片仍會垂直居中。
UIButtonConfiguration 內建 imagePadding 與 imagePlacement(.trailing 就是圖在右),一行設定即可,不必再繼承。