【发布时间】:2019-07-31 13:38:18
【问题描述】:
我正在尝试使用以下方法在属性字符串中创建链接:
matches = regex.matches(in: strings, options: [], range: NSRange(strings.startIndex..., in: strings))
for match in matches {
rangeBetweenQuotes = match.range(at: 1)
let swiftRange = Range(rangeBetweenQuotes, in: strings)!
let link:String = String(strings[swiftRange])
attributedString.addAttribute(.link, value: link, range: rangeBetweenQuotes)
}
如果我只是添加一个字体属性而不是一个链接,我知道上述方法是有效的。所以我的正则表达式有效。但是,在添加链接属性时,我遇到了问题。当我编译上面编写的代码并运行应用程序时,我点击链接并得到一个错误:线程 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0。它出现在应用程序委托类中。
据我所知,最后两行代码抛出了错误。
let link:String = String(strings[swiftRange])
attributedString.addAttribute(.link, value: link, range: rangeBetweenQuotes)
为了调试,我在上面的最后两行代码之间放置了一个断点。我可以看到变量 link 包含正确的字符串。该字符串也在addAttribute 的value 参数中找到。
在运行时点击链接时会引发错误。我知道是这种情况,因为我可以用字符串文字(即"test")替换或分配link,并且链接工作正常,我可以使用
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
将“测试”字符串文字分配给插座。
使用调试器,我在value 的value 参数中的link 变量内的向下钻取菜单中发现了以下内容addAttribute.
(BridgeObject) _object = 从值中提取数据失败
这表明变量有问题。不?
我尝试使用URL(string:"") 将String 类型的link 变量转换为URL,这也不起作用。
【问题讨论】:
标签: ios swift cocoa-touch nsattributedstring