Add NSUnderlineStyle.PatternDash to NSAttributedString in Swift?

大憨熊 提交于 2019-12-03 22:35:15

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

Swift 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

Swift 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

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.

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)

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]) 

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

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!