在开发中会遇到这样的需求,在lab或者是button下边需要下划线,现在举两个例子
1.在button下边加上下划线
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(100, 200, 200, 40);
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"我就是下划线"];
NSRange titleRange = {0,[title length]};
[title addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
[btn setAttributedTitle:title
forState:UIControlStateNormal];
[btn.titleLabel setFont:[UIFont systemFontOfSize:20]];
[self.view addSubview:btn];
2.在lab下边加上下划线
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 310, 350)];
[label setLineBreakMode:NSLineBreakByWordWrapping];
label.numberOfLines =0;
[label setFont:[UIFont systemFontOfSize:14]];
NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"乔丹 科比 詹姆斯 杜兰特 库里 韦德"]];
NSRange contentRange = {0,[content length]};
// 下划线
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
// 删除线
[content addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3,12)];
// 字体大小
[content addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, 2)];
// 字体颜色
[content addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, 10)];
// 删除线的颜色
[content addAttribute:NSStrikethroughColorAttributeName value:[UIColor greenColor] range:NSMakeRange(8, 10)];
label.attributedText = content;
[self.view addSubview:label];