Add NSUnderlineStyle.PatternDash to NSAttributedSt

2019-04-03 23:17发布

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条回答
\"骚年 ilove
2楼-- · 2019-04-03 23:33

Update for Swift 4 syntax:

Here's a full example of creating a UILabel with underlined text:

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

Swift 2:

Swift allows you to pass an Int to a method that takes an NSNumber, so you can make this a little cleaner by removing the conversion to NSNumber:

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

Note: This answer previously used toRaw() as used in the original question, but that is now incorrect as toRaw() has been replaced by the property rawValue as of Xcode 6.1.

查看更多
仙女界的扛把子
3楼-- · 2019-04-03 23:46

In Xcode 6.1, SDK iOS 8.1 toRaw() has been replaced by rawValue:

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

Or Easier :

 var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]) 
查看更多
Fickle 薄情
4楼-- · 2019-04-03 23:54

Turns out I needed the toRaw() method - this works:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
查看更多
放荡不羁爱自由
5楼-- · 2019-04-03 23:58

If you want an actual dashed line, you should OR | the raw values of both PatternDash and StyleSingle enums like below:

let dashed     =  NSUnderlineStyle.PatternDash.rawValue | NSUnderlineStyle.StyleSingle.rawValue

let attribs    = [NSUnderlineStyleAttributeName : dashed, NSUnderlineColorAttributeName : UIColor.whiteColor()];

let attrString =  NSAttributedString(string: plainText, attributes: attribs)
查看更多
登录 后发表回答