我正在尝试在我的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
线上得到了这个错误:
NSString
与NSObject
不同
如何将枚举中包含的属性添加到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))