Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString with strikethrough

Tags:

cocoa

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 whiteColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease];
like image 682
ambientdiscourse Avatar asked Feb 11 '11 19:02

ambientdiscourse


2 Answers

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]...
like image 167
Ole Begemann Avatar answered Nov 14 '22 05:11

Ole Begemann


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])
like image 21
Arnaud Nelissen Avatar answered Nov 14 '22 03:11

Arnaud Nelissen