iOS 给NSString文字中间或底部添加横线
程序员文章站
2023-12-23 12:54:52
...
给NSString类型的文字添加横线一种是添加到文字底部,一种是添加到文字中间
1.文字底部添加横线
NSMutableAttributedString *forgetTitle = [[NSMutableAttributedString alloc] initWithString:@"忘记密码"];
NSRange titleRange = {0,[forgetTitle length]};
[forgetTitle addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
[self.forgetPsdButton setAttributedTitle:forgetTitle
forState:UIControlStateNormal];
2.文字中间添加横线
self.oldPriceLabel.text = @"4500";
self.oldPriceLabel.textColor = [UIColor lightGrayColor];
NSMutableAttributedString *newPrice = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"$%@",self.oldPriceLabel.text]];
[newPrice addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, newPrice.length)];
self.oldPriceLabel.attributedText = newPrice;
文字中间添加删除线时有时候会无效果 原因可能是富文本不支持中文字符 解决方法如下
富文本支持中文 NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)
[newPrice setAttributes:@{NSStrikethroughStyleAttributeName: @(NSUnderlineStyleSingle), NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)} range:NSMakeRange(0,newPrice.length)];