CoreText and strikethrough on iPhone

Cyrille picture Cyrille · Jul 5, 2011 · Viewed 11.1k times · Source

I'm currently struggling with the need to display strikethrough text in many UITableViewCells. Something that written in HTML would looke like

<strike>€99</strike> save 50% => now €49

I don't want to use a UIWebView just for a single line of text, especially that it's used in small UITableViewCells. I know there are reusable cells and all, but I'd like to keep things the more memory-efficient way possible.

So... I'm using NSAttributedStrings, with the help of AliSoftware's UILabel-replacement OHAttributedLabel. The fact that it's only available starting with iOS 4.0 is no problem, as we use all kinds of stuff only 4.0-compatible.

I can manage to create the attributed string, it displays text in the OHAttributedLabel, OK, that's cool. But what I can't achieve is setting the "strikeout", or "strikethrough" attribute.

Basically I go like this:

NSString *price = [NSString stringWithFormat:@"%01.2f €", product.price];
NSString *rate = [NSString stringWithFormat:@" -%01.0f%%", product.reductionRate];

NSMutableAttributedString *s = [NSMutableAttributedString attributedStringWithString:price];

[s addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle] range:NSRangeFromString(price)];
[attributedLabel setAttributedText:s];

But here, the three NS* constants are undefined. I've imported CoreText.h, Foundation/NSAttributedString.h, to no avail. I've seen somewhere on the web that NSStrikethroughStyleAttributeName = @"NSStrikethroughStyleAttributeName", and that NSUnderlinePatternSolid = 0 and NSUnderlineStyleSingle = 1, but hard-coding these values don't give anything. One thing I got with auto-completion are the equivalent kCT...* constants, but there are kCTUnderlineStyleAttributeName, kCTStrokeWidthAttributeName, ... but no mention of kCTStrikethrough_anything.

What should I do to display that *$|#!@ piece of strike-through text ?

Answer

DenVog picture DenVog · Dec 5, 2012

With iOS 6 you can use NSStrikethroughStyleAttributeName

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

While it may seem out of place, the numberWithInt value is correct as NSUnderlineStyleSingle.