在NSift中将NSUnderlineStyle.PatternDash添加到NSAttributedString?

我正在尝试在我的Swift应用程序中为某些文本添加下划线。 这是我目前的代码:

let text = NSMutableAttributedString(string: self.currentHome.name) let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash] text.addAttributes(attrs, range: NSMakeRange(0, text.length)) homeLabel.attributedText = text 

但是我在text.addAttributes行上得到了这个错误:

NSStringNSObject

如何将枚举中包含的属性添加到Swift中的NSMutableAttributedString?

更新Swift 4语法:

以下是使用带下划线的文本创建UILabel的完整示例:

 let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30)) let text = NSMutableAttributedString(string: "hello, world!") let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue] text.addAttributes(attrs, range: NSRange(location: 0, length: text.length)) homeLabel.attributedText = text 

斯威夫特2:

Swift允许您将Int传递给一个带NSNumber的方法,因此您可以通过删除转换为NSNumber来使其更清洁:

 text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length)) 

注意:此答案之前使用过原始问题中使用的toRaw() ,但现在不正确,因为toRaw()已被Xcode 6.1中的属性rawValue替换。

如果你想要一个实际的虚线,你应该OR | PatternDash和StyleSingle枚举的原始值如下所示:

 let dashed = NSUnderlineStyle.PatternDash.rawValue | NSUnderlineStyle.StyleSingle.rawValue let attribs = [NSUnderlineStyleAttributeName : dashed, NSUnderlineColorAttributeName : UIColor.whiteColor()]; let attrString = NSAttributedString(string: plainText, attributes: attribs) 

在Xcode 6.1中,SDK iOS 8.1 toRaw()已被rawValue取代:

  text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length)) 

或更容易:

  var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]) 

结果我需要toRaw()方法 – 这有效:

 text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))