天天看点

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,如需转载请自行联系原作者