开发者

CoreText and strikethrough on iPhone

开发者 https://www.devze.com 2023-03-18 13:06 出处:网络
I\'m currently struggling with the need to display strikethrough text in many UITableViewCells. Something that written in HTML would looke like

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 d开发者_C百科on'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 ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消