ios开发中给label添加下划线和中划线。

在日常的iOS开发中很少会遇到给某个label添加中划线或者下划线的情况,但在某些电商类的app中我们经常会遇到某种商品打折优惠或者抢购的场景。并且为了吸引客户,商家一般把打折商品的现价和原价同时显示出来,进行对比,此时就出现了为展示原价的label添加中划线或者是下划线的需求。

如某旅游类app中显示:

Snip20160831_44

 

下面就我们直接上代码:

添加中划线:
  UILabel * strikeLabel = [[UILabel alloc] initWithFrame:(CGRectMake(10, 10, 50, 30))];
  NSString *textStr = [NSString stringWithFormat:@"%@元", primeCost];

  //中划线
  NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
  NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];

  // 赋值
  strikeLabel.attributedText = attribtStr;

  [self.view addSubview:strikeLabel];
添加下划线:
  UILabel *underlineLabel = [[UILabel alloc] initWithFrame:(CGRectMake(10, 10, 50, 30))];
  NSString *textStr = [NSString stringWithFormat:@"%@元", primeCost];

  // 下划线
  NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
  NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];

  //赋值
  underlineLabel.attributedText = attribtStr;

  [self.view addSubview:underlineLabel];

效果如图所示:

Snip20160831_45

OK 大功告成~