美文网首页iOS新手学习
iOS --- UILabel添加中划线和下划线

iOS --- UILabel添加中划线和下划线

作者: 鑫飞 | 来源:发表于2017-08-07 14:10 被阅读37次

    1.

        UILabel *lbl_oldPrice = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 30)];
        lbl_oldPrice.font = [UIFont systemFontOfSize:14];
        lbl_oldPrice.backgroundColor = [UIColor greenColor];
        NSString *textStr = @"¥199";
      
        //中划线
        NSDictionary *attribtDic1 = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr1 = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic1];
        lbl_oldPrice.attributedText = attribtStr1;
        
        // 下划线
        NSDictionary *attribtDic2 = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr2 = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic2];
        lbl_oldPrice.attributedText = attribtStr2;
        lbl_oldPrice.attributedText = attribtStr1;
        
        lbl_oldPrice.textColor = [UIColor grayColor];
        lbl_oldPrice.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:lbl_oldPrice];
    

    2.

    iOS10.3更新后,商城APP这样的UI:原价 “¥500 ” 类似Label设置的中划线突然失效了。
    这可能是苹果系统的一个bug。
    根本原因:UILabel上的文字只要包含有“中文”,富文本字符串的中划线就会失效,我们可通过以下两种方式解决。

    第一种方式:人民币符号“¥”和“¥”,使用前面一个即可。
    NSString *market = [NSString stringWithFormat:@"¥%@",@"500"];
    NSMutableAttributedString *attributeMarket = [[NSMutableAttributedString alloc] initWithString:market];
    [attributeMarket setAttributes:@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,market.length)];
    
    _marketLabel.attributedText = attributeMarket;
    
    第二种方式:让富文本支持“中文”

    增加一个富文本属性: NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)

    NSString *market = [NSString stringWithFormat:@"¥%@",@"500"];
    NSMutableAttributedString *attributeMarket = [[NSMutableAttributedString alloc] initWithString:market];
    [attributeMarket setAttributes:@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)} range:NSMakeRange(0,market.length)];
    
    _marketLabel.attributedText = attributeMarket;
    

    相关文章

      网友评论

        本文标题:iOS --- UILabel添加中划线和下划线

        本文链接:https://www.haomeiwen.com/subject/ecxalxtx.html