2014-09-01 222 views
17

我试图给我的Swift应用程序中的某些文本添加下划线。这是代码我目前:在Swift中添加NSUnderlineStyle.PatternDash到NSAttributedString?

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

我如何添加包含属性在一个枚举NSMutableAttributedString在Swift中?

回答

43

更新雨燕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:

斯威夫特允许您将Int传递给需要一个NSNumber的方法,这样你就可以通过删除转化为NSNumber使这一点清洁:

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

注:此回答以前使用的原始问题中使用的toRaw(),但是现在不正确,因为toRaw()已由Xcode 6.1中的属性rawValue取代。

+0

请问您可以用swift4语法更新您的代码。 – Vats 2017-12-27 11:08:36

+0

@Vats,已更新。看一看。 – vacawama 2017-12-27 13:59:50

3

原来我需要toRaw()方法 - 这个工程:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length)) 
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]) 
13

如果你想要一个实际的虚线,你应该还是| PatternDash和StyleSingle枚举的原始值如下:

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

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

let attrString = NSAttributedString(string: plainText, attributes: attribs)