需求很明確:做出下圖右側那種帶底線的按鈕文字效果。

UIButton 的 setTitle:forState: 只接受純文字,畫不出底線。要加上底線,得改用 NSAttributedString 並透過 setAttributedTitle:forState: 套用。
[MyTools createMyImageview:topEditView
frame:CGRectMake(widthAll - 90, 12, 17, 16)
imageName:@"離線課程_下載更多.png"];
UIButton *downMoreButton = [MyTools createMyBtn:@"下載更多"
frame:CGRectMake(widthAll - 70, 10, 60, 20)
uiview:topEditView
uifont:14
color:[UIColor colorWithRed:92/255.0
green:218/255.0
blue:231/255.0
alpha:1]];
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"下載更多"];
NSRange titleRange = {0, [title length]};
[title addAttribute:NSUnderlineStyleAttributeName
value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
range:titleRange];
[downMoreButton setAttributedTitle:title forState:UIControlStateNormal];
[downMoreButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
[downMoreButton addTarget:self
action:@selector(downMore)
forControlEvents:UIControlEventTouchUpInside];
關鍵只有三步:建立可變的 attributed string、用 NSUnderlineStyleAttributeName 指定底線樣式並設定範圍、最後改用 setAttributedTitle: 套用。
補充幾個實務上的小提醒:
NSUnderlineStyleSingle,還有 Thick、Double 以及 NSUnderlinePatternDot 等虛線/點線搭配,可用位移運算組合。NSUnderlineColorAttributeName 控制,不設定時會跟隨文字顏色。titleLabel.font 或 NSFontAttributeName 一併指定,否則容易出現字型不一致。以上就是為 iOS 按鈕文字加上底線的完整做法。