I'm currently struggling with the need to display strikethrough text in many UITableViewCell
s. Something that written in HTML would looke like
<strike>€99</strike> save 50% => now €49
I d开发者_C百科on't want to use a UIWebView
just for a single line of text, especially that it's used in small UITableViewCell
s. 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 NSAttributedString
s, 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 ?
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.
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.
精彩评论