带有删除线的NSAttributedString

amb*_*rse 15 cocoa

我正在尝试使用删除线创建一个属性字符串,但是,这个简单的任务似乎比我预期的更难理解.这是我目前的(不起作用).谢谢您的帮助!

NSAttributedString *theTitle = [[[NSAttributedString alloc] initWithString:@"strikethrough text" attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor whiteColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease];
Run Code Online (Sandbox Code Playgroud)

Ole*_*ann 20

首先,值NSStrikethroughStyleAttributeName必须是a NSNumber,而不是简单的整数.其次,我认为你必须包括NSUnderlineStyleSingle:

...:[NSDictionary dictionaryWithObjectsAndKeys:
      ..., 
      [NSNumber numberWithInteger:NSUnderlinePatternSolid | NSUnderlineStyleSingle], 
      NSStrikethroughStyleAttributeName, 
      nil]...
Run Code Online (Sandbox Code Playgroud)


Arn*_*sen 16

你也可以简单地使用:

NSAttributedString *theAttributedString;
theAttributedString = [[NSAttributedString alloc] initWithString:theString 
            attributes:@{NSStrikethroughStyleAttributeName:
            [NSNumber numberWithInteger:NSUnderlineStyleSingle]}];
Run Code Online (Sandbox Code Playgroud)

更新:

Swift 2.0版

let theAttributedString = NSAttributedString(string: theString, attributes: [NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle])
Run Code Online (Sandbox Code Playgroud)

  • 这是错误的,您不能将样式分配给color属性。`[NSStrikethroughColorAttributeName:NSUnderlineStyle.StyleSingle]` (2认同)