您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 按鈕文字加上底線:用 NSAttributedString 實作

編輯:iOS 相關教學

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

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 控制,不設定時會跟隨文字顏色。
  • 一旦改用 attributed title,字型也要記得透過 titleLabel.font 或 NSFontAttributeName 一併指定,否則容易出現字型不一致。
  • 若同時有 normal 與 highlighted 兩種狀態,兩邊都要各自設定 attributed title。

以上就是為 iOS 按鈕文字加上底線的完整做法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved