ios Lable 添加删除线

遇到坑了:

    NSString *goodsPrice = @"230.39";
    NSString *marketPrice = @"299.99";
    NSString* prceString = [NSString stringWithFormat:@"%@ %@",goodsPrice,marketPrice];
    DLog(@"----打印--%@---",prceString);

 NSMutableAttributedString*attributedString = [[NSMutableAttributedString alloc]initWithString:prceString];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:RGBACOLOR(253, 91, 120, 1) range:NSMakeRange(0, goodsPrice.length)];
    
    [attributedString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid|NSUnderlineStyleSingle) range:[prceString rangeOfString:marketPrice]];
    
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:[prceString rangeOfString:marketPrice]];
    
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:[prceString rangeOfString:marketPrice]];
    [priceLabel setAttributedText:attributedString];

我感觉下面的代码写的没有问题,但是运行起来怎么就不行了呢

真是百思不得姐,然后各种百度:http://stackoverflow.com/questions/43070335/nsstrikethroughstyleattributename-how-to-strike-out-the-string-in-ios-10-3

然后然后...,换了种写法:

    NSString *goodsPrice = @"230.39";
    NSString *marketPrice = @"299.99";
    NSString* prceString = [NSString stringWithFormat:@"%@ %@",goodsPrice,marketPrice];
    DLog(@"----打印--%@---",prceString);
    
    NSMutableAttributedString *attritu = [[NSMutableAttributedString alloc]initWithString:prceString];
    [attritu addAttributes:@{
                             NSStrikethroughStyleAttributeName:@(NSUnderlineStyleThick),
                             NSForegroundColorAttributeName:
                                 [UIColor lightGrayColor],
                             NSBaselineOffsetAttributeName:
                                 @(0),
                             NSFontAttributeName: [UIFont systemFontOfSize:14]
                             } range:[prceString rangeOfString:marketPrice]];
    priceLabel.attributedText = attritu;

如果上面的问题还有问题,我们还可以用其他方式实现这种效果

新建一个集成 UILabel 的子类,

- (void)drawRect:(CGRect)rect
{
    // 调用super的drawRect:方法,会按照父类绘制label的文字
    [super drawRect:rect];
    
    // 取文字的颜色作为删除线的颜色
    [self.textColor set];
    CGFloat w = rect.size.width;
    CGFloat h = rect.size.height;
    // 绘制(这个数字是为了找到label的中间位置,0.35这个数字是试出来的,如果不在中间可以自己调整)
    UIRectFill(CGRectMake(0, h * 0.5, w, 1));
}

别忘了sizeToFit 不然线会根据空间的 width来画的

    YJlale *priceLabel = [[YJlale alloc] initWithFrame:CGRectMake(20, 20, 200, 20)];
    priceLabel.textColor = [UIColor redColor];
    priceLabel.text = @"1234";
    [priceLabel sizeToFit];
    [self.view addSubview:priceLabel];

 

posted @ 2017-04-11 20:04  _水畔竹汐  阅读(1953)  评论(0编辑  收藏  举报