在NSift中将NSUnderlineStyle.PatternDash添加到NSAttributedString? [英] Add NSUnderlineStyle.PatternDash to NSAttributedString in Swift?
问题描述
我正在尝试在我的Swift应用中为某些文字添加下划线。这是我目前的代码:
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
但我在 text.addAttributes
行上收到此错误:
But I get this error on the text.addAttributes
line:
NSString
与NSObject不同
如何将枚举中包含的属性添加到Swift中的NSMutableAttributedString?
How can I add an attribute contained in an enum to an NSMutableAttributedString in Swift?
推荐答案
更新 Swift 4 语法:
这是一个完整的使用带下划线的文本创建 UILabel
的示例:
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允许您将 Int
传递给采用 NSNumber $ c的方法$ c>,所以你可以通过删除转换为
NSNumber
来使这个更清洁:
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))
注意:此答案以前使用原始问题中使用的 toRaw()
,但现在这个答案不正确 toRaw()
已被属性 rawValue
取代。
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.
这篇关于在NSift中将NSUnderlineStyle.PatternDash添加到NSAttributedString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!