NSAttributedString with strikethrough
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]...
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)
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
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])