这是创建UILabel
带下划线文本的完整示例:
斯威夫特 5:
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
斯威夫特 4:
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 允许您将 an 传递Int
给接受 an 的方法NSNumber
,因此您可以通过删除对 的转换来使其更简洁NSNumber
:
text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length))
注意:这个答案以前toRaw()
在原始问题中使用过,但现在不正确,因为从 Xcode 6.1开始,toRaw()
它已被属性替换。rawValue