开发者

NSAttributedString with strikethrough

开发者 https://www.devze.com 2023-02-10 13:41 出处:网络
I\'m trying to create an attributed string with a strikethrough, however, this simple task seems to be harder to figure out than I anticipated.Here is what I have currently (which is not working). Tha

I'm trying to create an attributed string with a strikethrough, however, this simple task seems to be harder to figure out than I anticipated. Here is what I have currently (which is not working). Thanks for the help!

NSAttributedString *theTitle = [[[NSAttributedString alloc] initWithString:@"strikethrough text" attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor whi开发者_JAVA技巧teColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease];


First, the value for NSStrikethroughStyleAttributeName must be an NSNumber, not a simple integer. Second, I think you have to include NSUnderlineStyleSingle:

...:[NSDictionary dictionaryWithObjectsAndKeys:
      ..., 
      [NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle], 
      NSStrikethroughStyleAttributeName, 
      nil]...


You can also simply use:

NSAttributedString *theAttributedString;
theAttributedString = [[NSAttributedString alloc] initWithString:theString 
            attributes:@{NSStrikethroughStyleAttributeName:
            [NSNumber numberWithInteger:NSUnderlineStyleSingle]}];

Update :

Swift 2.0 version

let theAttributedString = NSAttributedString(string: theString, attributes: [NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle])


func addAttributes(attrs: [String : AnyObject], range: NSRange)

NSUnderlineStyleAttributeName: The value of this attribute is an NSNumber object containing an integer.

Since the NSUnderlineStyle enum's rawValue is Int Type, you should initialize a NSNumber Object with it

Swift2.1:

attrStr.addAttributes([NSStrikethroughStyleAttributeName: NSNumber(integer: NSUnderlineStyle.StyleSingle.rawValue)], range: NSMakeRange(x, y))

x is the location, the start of your text

y is the length of the text


Swift 4:

NSAttributedString(string: "test string", attributes: [.strikethroughStyle: NSUnderlineStyle.styleSingle.rawValue])

Swift 5:

NSAttributedString(string: "test string", attributes: [.strikethroughStyle: NSUnderlineStyle.single.rawValue])

Mind the fact that .strikethroughStyle and .underlineStyle expect an integer value (specifically an NSNumber), therefore we're using NSUnderlineStyle's .rawValue in the examples. (Setting NSUnderlineStyle causes unrecogognized selector exception)

0

精彩评论

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