iOS开发-UILabel和UIButton添加下划线

十度 IOS 2015年12月01日 收藏

关于UILabel和UIButton有的时候需要添加下划线,一般有两种方式通过默认的NSMutableAttributedString设置,第二种就是在drawRect中画一条下划线,本文就简单的选择第一种,第二种有兴趣的可以自己研究一下。

UILabel设置下划线:

  1. UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 310, 50)];
  2. label.backgroundColor = [UIColor redColor];
  3. [label setLineBreakMode:NSLineBreakByWordWrapping];
  4. label.numberOfLines =3;
  5. [label setFont:[UIFont systemFontOfSize:14]];
  6. NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"博文地址:http://www.cnblogs.com/xiaofeixiang 博客园-FlyElephant QQ群:228407086"]];
  7. NSRange contentRange = {0,[content length]};
  8. [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
  9. label.attributedText = content;
  10. [self.view addSubview:label];

UIButton设置下划线:

  1. UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(10, 200, 80, 30)];
  2. NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"FlyElephant"];
  3. NSRange titleRange = {0,[title length]};
  4. [title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
  5. [button setAttributedTitle:title
  6. forState:UIControlStateNormal];
  7. [button setBackgroundColor:[UIColor redColor]];
  8. [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
  9. [self.view addSubview:button];

最终效果如下: