您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

為 UIButton 標題加上底線的實作方式

編輯:iOS 開發綜合

需求很單純:讓按鈕上的文字帶一條下劃線,如下圖右側那顆按鈕。

做法:改用 attributedTitle

UIButton 的 setTitle:forState: 只吃純文字,畫不出底線;改用 NSAttributedString 就能指定底線樣式:

[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];

幾個實務細節

一是底線顏色會跟著文字顏色走,NSUnderlineStyleAttributeName 只能控制粗細樣式(單線、雙線、粗線),若要不同顏色得額外加上 NSUnderlineColorAttributeName。

二是使用 attributedTitle 之後,setTitleColor:forState: 就對文字無效了,顏色必須寫進 attributes 字典,這點在處理點擊態(highlighted)時特別容易忘記,導致按下時文字不變色。

三是若用 setFont: 設字級,記得同時把字型寫進 attributes,否則高亮狀態切換時字型可能被還原成系統預設。

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