将NSUnderlineStyle.PatternDash添加到Swift中的NSAttributedString?

问题描述 投票:19回答:4

我正在尝试在我的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线上得到了这个错误:

NSStringNSObject不同

如何将枚举中包含的属性添加到Swift中的NSMutableAttributedString?

ios swift nsattributedstring nsmutableattributedstring
4个回答
48
投票

更新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所取代。


13
投票

如果你想要一个实际的虚线,你应该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)

7
投票

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

3
投票

结果我需要toRaw()方法 - 这有效:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length))
© www.soinside.com 2019 - 2024. All rights reserved.