添加中划线:
UILabel* strikeLabel = [[UILabelalloc] initWithFrame:(CGRectMake(10,10,50,30))];NSString*textStr = [NSStringstringWithFormat:@"%@元", primeCost];//中划线NSDictionary*attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumbernumberWithInteger:NSUnderlineStyleSingle]};NSMutableAttributedString*attribtStr = [[NSMutableAttributedStringalloc]initWithString:textStr attributes:attribtDic];// 赋值strikeLabel.attributedText= attribtStr; [self.viewaddSubview:strikeLabel];
UILabel*underlineLabel = [[UILabelalloc] initWithFrame:(CGRectMake(10,10,50,30))];NSString*textStr = [NSStringstringWithFormat:@"%@元", primeCost];// 下划线NSDictionary*attribtDic = @{NSUnderlineStyleAttributeName: [NSNumbernumberWithInteger:NSUnderlineStyleSingle]};NSMutableAttributedString*attribtStr = [[NSMutableAttributedStringalloc]initWithString:textStr attributes:attribtDic];//赋值underlineLabel.attributedText= attribtStr; [self.viewaddSubview:underlineLabel];
但是 我发现到了ios10以后 该方法就失效了。根本原因:Label上的文字只要包含有“中文”,富文本字符串的中划线就会失效,我们可通过以下方式解决。
让富文本支持“中文”:
NSString*market = [NSStringstringWithFormat:@"¥%@",@"500"];
NSMutableAttributedString *attributeMarket = [[NSMutableAttributedString alloc] initWithString:market];
[attributeMarket setAttributes:@{NSStrikethroughStyleAttributeName: [NSNumbernumberWithInteger:NSUnderlineStyleSingle], NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)} range:NSMakeRange(0,market.length)];
_marketLabel.attributedText= attributeMarket;
到此,目前你可以按照以上方式来解决,相信苹果会在下一版本解决这个bug。