【问题标题】:NSAttributedString with strikethrough带有删除线的 NSAttributedString
【发布时间】:2011-02-11 19:38:16
【问题描述】:

我正在尝试创建一个带有删除线的属性字符串,但是,这个简单的任务似乎比我预期的更难弄清楚。这是我目前拥有的(不起作用)。感谢您的帮助!

NSAttributedString *theTitle = [[[NSAttributedString alloc] initWithString:@"strikethrough text" attributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSColor whiteColor], NSForegroundColorAttributeName, NSUnderlinePatternSolid, NSStrikethroughStyleAttributeName, nil]] autorelease];

【问题讨论】:

    标签: cocoa


    【解决方案1】:

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

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

    【讨论】:

    • 这很有帮助。谢谢!值得注意的是,您缺少一个右括号来关闭NSUnderlinePatternSolid | NSUnderlineStyleSingle 之后和, NSStrikethroughStyleAttributeName 之前的numberWithInteger: 消息。
    【解决方案2】:

    您也可以简单地使用:

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

    更新:

    Swift 2.0 版本

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

    【讨论】:

    • 这是错误的,您不能将样式分配给颜色属性。 [NSStrikethroughColorAttributeName: NSUnderlineStyle.StyleSingle]
    【解决方案3】:
    func addAttributes(attrs: [String : AnyObject], range: NSRange)
    

    NSUnderlineStyleAttributeName: 该属性的值是一个包含整数的NSNumber 对象。

    由于NSUnderlineStyle枚举的rawValue是Int类型,你应该用它初始化一个NSNumber对象

    Swift2.1:

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

    x 是位置,文本的开头

    y 是文本的长度

    【讨论】:

    • Range is not Working when I write NSRangeMake(0, 4) that doesn't work ,如果我写 NSRangeMake(0, theAttributedString.lenght) 那工作,但我要求只在 String 上的前四个字符上放置水平线,怎么能我这样做.??
    • iOS 10.3 中存在一个已知错误,如果应用在范围内,删除线属性将不起作用。作为一种解决方法,您可以这样做:attrStr.addAttributes([NSBaselineOffsetAttributeName: NSNumber(integerLiteral: 0)], range: NSMakeRange(x, y))
    【解决方案4】:

    斯威夫特 4:

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

    斯威夫特 5:

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

    请注意.strikethroughStyle.underlineStyle 需要一个整数值(特别是NSNumber),因此我们在示例中使用NSUnderlineStyle.rawValue。 (Setting NSUnderlineStyle causes unrecogognized selector exception)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多