天天看點

iOS開發-UILabel和UIButton添加下劃線

關于UILabel和UIButton有的時候需要添加下劃線,一般有兩種方式通過預設的NSMutableAttributedString設定,第二種就是在drawRect中畫一條下劃線,本文就簡單的選擇第一種,第二種有興趣的可以自己研究一下。

UILabel設定下劃線:

1

2

3

4

5

6

7

8

9

10

11

<code>UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 310, 50)];</code>

<code>label.backgroundColor = [UIColor redColor];</code>

<code>[label setLineBreakMode:</code><code>NSLineBreakByWordWrapping</code><code>];</code>

<code>label.numberOfLines =3;</code>

<code>[label setFont:[UIFont systemFontOfSize:14]];</code>

<code>NSMutableAttributedString</code> <code>*content = [[</code><code>NSMutableAttributedString</code> <code>alloc]initWithString:[</code><code>NSString</code> <code>stringWithFormat:@</code><code>"博文位址:http://www.cnblogs.com/xiaofeixiang 部落格園-FlyElephant QQ群:228407086"</code><code>]];</code>

<code>NSRange</code> <code>contentRange = {0,[content length]};</code>

<code>[content addAttribute:</code><code>NSUnderlineStyleAttributeName</code> <code>value:[</code><code>NSNumber</code> <code>numberWithInteger:</code><code>NSUnderlineStyleSingle</code><code>] range:contentRange];</code>

<code>label.attributedText = content;</code>

<code>[</code><code>self</code><code>.view addSubview:label];</code>

UIButton設定下劃線:

<code>UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(10, 200, 80, 30)];</code>

<code>  </code><code>NSMutableAttributedString</code> <code>*title = [[</code><code>NSMutableAttributedString</code> <code>alloc] initWithString:@</code><code>"FlyElephant"</code><code>];</code>

<code>  </code><code>NSRange</code> <code>titleRange = {0,[title length]};</code>

<code>  </code><code>[title addAttribute:</code><code>NSUnderlineStyleAttributeName</code> <code>value:[</code><code>NSNumber</code> <code>numberWithInteger:</code><code>NSUnderlineStyleSingle</code><code>] range:titleRange];</code>

<code>  </code><code>[button setAttributedTitle:title</code>

<code>                    </code><code>forState:UIControlStateNormal];</code>

<code>  </code><code>[button setBackgroundColor:[UIColor redColor]];</code>

<code>  </code><code>[button.titleLabel setFont:[UIFont systemFontOfSize:14]];</code>

<code>  </code><code>[</code><code>self</code><code>.view addSubview:button];</code>

最終效果如下:

iOS開發-UILabel和UIButton添加下劃線

本文轉自Fly_Elephant部落格園部落格,原文連結:http://www.cnblogs.com/xiaofeixiang/p/4582292.html,如需轉載請自行聯系原作者

繼續閱讀