【发布时间】:2016-10-07 23:10:18
【问题描述】:
在NSAttributedString 中,一系列字母具有链接属性和自定义颜色属性。
在带有 Swift 2 的 Xcode 7 中,它可以工作:
在带有 Swift 3 的 Xcode 8 中,链接的自定义属性颜色总是被忽略(在屏幕截图中应该是橙色)。
这是测试代码。
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
我已向 Apple 发送了一份错误报告,但与此同时,如果有人对 Xcode 8 中的修复或解决方法有想法,那就太好了。
【问题讨论】:
-
使用
NSTextView时,必须设置linkTextAttributes属性。当NSTextField获得焦点并可以编辑时,文本将显示在NSTextView中,该linkTextAttributes使用其linkTextAttributes(默认为蓝色,带下划线和手形光标)。 -
@Willeke 谢谢,不幸的是我已经尝试过覆盖linkTextAttributes,这是一个很好的解决方案,但是它将相同的属性应用于属性字符串中的所有链接,我需要能够设置不同的属性。问题是,你对我另一个问题的回答直到最近才起作用,这里最大的谜团是为什么你回答的完全相同的代码不再起作用了。 :)
-
哦。该链接在 Xcode 7 中为橙色。在 Xcode 8 中为蓝色。我正在归档雷达...抱歉打扰您了,@Willeke...
-
"htpp"??????? -
而且下划线也是新的。它曾经没有下划线(如您的第一个屏幕截图所示)。基本上他们使文本视图链接看起来像一个标签链接。这可能是故意的;以前很混乱。
标签: swift cocoa xcode8 nsattributedstring nstextfield