UIButton 預設的排列是圖片與文字各自居中,兩者之間還留著一段 system spacing。想做成「小圖示 + 緊貼文字」的列表樣式,直接拉 frame 是沒用的,得動 imageEdgeInsets 與 titleEdgeInsets。
關鍵觀念:這兩個 inset 的位移方向與一般直覺相反——正值會把內容往「反方向」推,所以右邊要留多少空白,得用「螢幕寬度減去目標值」這種算法來表達。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = RGB(235, 235, 240);
UIButton *oneButton = [[UIButton alloc] initWithFrame:CGRectMake(0, kHeaderHeight + 8, kScreenWidth, 40)];
[oneButton setImage:[UIImage imageNamed:@"icon_party_knowledge_rights_obligations"]
forState:UIControlStateNormal];
[oneButton setTitle:@"第一個" forState:UIControlStateNormal];
oneButton.titleLabel.font = FONT(12);
[oneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[oneButton setImageEdgeInsets:UIEdgeInsetsMake(2, 8, 0, kScreenWidth - 50)];
[oneButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, kScreenWidth - 100)];
oneButton.backgroundColor = [UIColor whiteColor];
[oneButton addTarget:self action:@selector(oneButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:oneButton];
UIButton *twoButton = [[UIButton alloc] initWithFrame:CGRectMake(0, oneButton.maxY + 8, kScreenWidth, 40)];
[twoButton setImage:[UIImage imageNamed:@"icon_party_knowledge_dues_collection_standard"]
forState:UIControlStateNormal];
[twoButton setTitle:@"第二個" forState:UIControlStateNormal];
twoButton.titleLabel.font = FONT(12);
[twoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[twoButton setImageEdgeInsets:UIEdgeInsetsMake(2, 8, 0, kScreenWidth - 50)];
[twoButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, kScreenWidth - 100)];
twoButton.backgroundColor = [UIColor whiteColor];
[twoButton addTarget:self action:@selector(twoButtonAction:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:twoButton];
// 右箭頭
for (int i = 0; i < 2; i++) {
UIImageView *rightImgView = [[UIImageView alloc]
initWithFrame:CGRectMake(kScreenWidth - 20, kHeaderHeight + 20 + i * 48, 7, 12)];
rightImgView.image = [UIImage imageNamed:@"icon_right"];
[self.view addSubview:rightImgView];
}
}
完成的樣式如下:

edgeInsets 這種「用負空間推元素」的寫法很吃經驗,也容易在換字型或換語言時走位。若想避開這些算術,可以改用 configuration(iOS 15 起)的 UIButton.Configuration,設 imagePadding 與 imagePlacement = .leading,系統會自動幫你排好;在舊系統上則可以自訂一個 view,用兩個子 view 加 stack 排版,可控性更高。