Und*_*ndo 19 nsattributedstring ios nsmutableattributedstring swift
我正在尝试在我的Swift应用程序中为某些文本添加下划线.这是我目前的代码:
let text = NSMutableAttributedString(string: self.currentHome.name)
let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash]
text.addAttributes(attrs, range: NSMakeRange(0, text.length))
homeLabel.attributedText = text
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误text.addAttributes:
NSString与...不完全相同NSObject
如何将枚举中包含的属性添加到Swift中的NSMutableAttributedString?
vac*_*ama 49
更新Swift 4语法:
以下是创建UILabel带下划线文本的完整示例:
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
Run Code Online (Sandbox Code Playgroud)
斯威夫特2:
Swift允许你传递Int给一个带有的方法NSNumber,所以你可以通过删除转换为NSNumber:
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
Run Code Online (Sandbox Code Playgroud)
注意:此答案以前toRaw()在原始问题中使用,但现在不正确,因为toRaw()已被rawValueXcode 6.1中的属性所取代.
Ric*_*Fox 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)
Run Code Online (Sandbox Code Playgroud)
在Xcode 6.1中,SDK iOS 8.1 toRaw()已被替换为rawValue:
text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))
Run Code Online (Sandbox Code Playgroud)
或更容易:
var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13592 次 |
| 最近记录: |