3

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 ?

Cyrille
  • 25,014
  • 12
  • 67
  • 90
  • http://www.cocoanetics.com/2011/01/befriending-core-text/ Works GREAT for me...enjoy! –  Aug 16 '11 at 22:54

2 Answers2

7

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.

DenVog
  • 4,226
  • 3
  • 43
  • 72
  • 2
    Still, if you use Core Text to render the attributed string, it will not render strikethrough line, even in iOS7.1 – Léo Natan Feb 27 '14 at 15:33
2

A simpler approach might be two labels, using the answer to this question - Pixel Width of the text in a UILabel - to strikeout the text in one of the labels.

Community
  • 1
  • 1
Mike Rhodes
  • 1,816
  • 12
  • 15