Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString Strikethrough makes my attributed text disappear

I am trying to make an attributed string with a strikethrough. I can set other attributes such as foreground color and font size but when I try to set a strikethrough through part of the text, that part of the text disappears. Any Idea what might be causing it?

Below is the code. Thanks for looking!

// ...    
    //Price
    NSLog(@"RESULT NUMBER %d", cell.result.resultId);
    priceString = (priceString == nil) ? @"$150.00\n$100.00" : priceString;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:priceString];
    NSRange linebreak = [priceString rangeOfString:@"\n"];



    if (linebreak.location != NSNotFound) {
        [attributedString beginEditing];
        // RegPrice
        NSRange firstLine = NSMakeRange(0, linebreak.location);
//        [attributedString addAttribute:NSFontAttributeName
//                                 value:[UIFont boldSystemFontOfSize:11]
//                                 range:firstLine];
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1]
                                 range:firstLine];
        @try {
            [attributedString addAttribute:NSStrikethroughStyleAttributeName
                                     value:@(NSUnderlineStyleSingle)
                                     range:firstLine];
        } @catch (NSException *e) {
            NSLog(@"ATTRIBUTE EXCEPTION: %@", e);
        }

        // Sale Price
        [attributedString addAttribute:NSFontAttributeName
                                 value:[UIFont boldSystemFontOfSize:14]
                                 range:NSMakeRange(linebreak.location + 1, priceString.length - (linebreak.location + 1))];
        [attributedString endEditing];
    }
    cell.lblPrice.attributedText = attributedString;

    return cell;
}
like image 503
ThinkBonobo Avatar asked Jun 26 '26 00:06

ThinkBonobo


1 Answers

I had the same problem of string disappearing until I realised that the value for NSStrikethroughStyleAttributeName should be an NSNumber.

Therefore the code above should look like:

Objective-c

[attributedString addAttribute:NSStrikethroughStyleAttributeName 
                         value: [NSNumber numberWithInt: NSUnderlineStyleSingle] 
                         range:firstLine];

In Swift 4 attributes are passed using dictionary of type [NSAttributedStringKey: Any] and the strike trough style attribute would look like this:

[NSAttributedStringKey.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)]
like image 186
gabbo Avatar answered Jun 28 '26 14:06

gabbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!