20

I'm trying to add an underline to some text in my Swift app. This is the code I have currently:

let text = NSMutableAttributedString(string: self.currentHome.name)

let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]

text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text

But I get this error on the text.addAttributes line:

NSString is not identical to NSObject

How can I add an attribute contained in an enum to an NSMutableAttributedString in Swift?

4

4 回答 4

52

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

斯威夫特 5:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))

let text = NSMutableAttributedString(string: "hello, world!")

let attrs = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.single.rawValue]

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length))

homeLabel.attributedText = text

斯威夫特 4:

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 允许您将 an 传递Int给接受 an 的方法NSNumber,因此您可以通过删除对 的转换来使其更简洁NSNumber

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

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

于 2014-09-02T00:21:27.403 回答
14

如果你想要一条实际的虚线,你应该 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)
于 2015-06-03T22:30:24.030 回答
7

在 Xcode 6.1 中,SDK iOS 8.1toRaw()已被替换为rawValue

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

或者更简单:

 var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]) 
于 2014-10-23T08:41:06.897 回答
3

原来我需要这个toRaw()方法——这个方法有效:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
于 2014-09-01T19:32:42.370 回答