NSAttributedString
中,一段字母具有链接属性和自定义颜色属性。在使用Swift 2的Xcode 7中,它可以工作: 在Xcode 8中使用Swift 3,链接的自定义属性颜色总是被忽略了(截图中应该是橙色)。
这是用于测试的代码。
Swift 2,Xcode 7:
import Cocoa
import XCPlayground
let text = "Hey @user!"
let attr = NSMutableAttributedString(string: text)
let range = NSRange(location: 4, length: 5)
attr.addAttribute(NSForegroundColorAttributeName, value: NSColor.orangeColor(), range: range)
attr.addAttribute(NSLinkAttributeName, value: "http://somesite.com/", range: range)
let tf = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 50))
tf.allowsEditingTextAttributes = true
tf.selectable = true
tf.stringValue = text
tf.attributedStringValue = attr
XCPlaygroundPage.currentPage.liveView = tf
Swift 3,Xcode 8:
import Cocoa
import PlaygroundSupport
let text = "Hey @user!"
let attr = NSMutableAttributedString(string: text)
let range = NSRange(location: 4, length: 5)
attr.addAttribute(NSForegroundColorAttributeName, value: NSColor.orange, range: range)
attr.addAttribute(NSLinkAttributeName, value: "http://somesite.com/", range: range)
let tf = NSTextField(frame: NSRect(x: 0, y: 0, width: 200, height: 50))
tf.allowsEditingTextAttributes = true
tf.isSelectable = true
tf.stringValue = text
tf.attributedStringValue = attr
PlaygroundPage.current.liveView = tf
我已向苹果发送了一个错误报告,但如果有人在Xcode 8中有修复或解决方法的想法,那将是很棒的。
NSTextView
时,必须设置linkTextAttributes
属性。当NSTextField
获得焦点并且可以编辑时,文本将显示在NSTextView
中,该视图使用其linkTextAttributes
(默认为蓝色、带下划线和手形光标)。 - Willeke