Reputation: 16545
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;
}
Upvotes: 3
Views: 2187
Reputation: 501
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)]
Upvotes: 6
Reputation: 883
I had the problem with the strikethrough text disappearing in a UILabel in iOS 7.0 only. It works fine in iOS 6.1 and 7.1.
There seems to be a bug in iOS 7.0 that strikethrough text disappears if the label is too high for the text by a certain amount. It works when I set the label's frame to a small enough height or call sizeToFit after setting the attributedText.
Upvotes: 0
Reputation: 725
For me boldSystemFontOfSize: returns a font object with the HelveticaNeueInterface-MediumP4 font. Are you sure this font has a strike-through? Not all fonts do. Maybe try using a different font, one that you know has a strike-through.
Upvotes: 0