CoreText and strikethrough on iPhone

丶灬走出姿态 提交于 2019-12-22 10:07:26

问题


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 ?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/6579270/coretext-and-strikethrough-on-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!