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];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM