【发布时间】:2019-01-28 08:17:12
【问题描述】:
我正在处理由NSAttributedString 填充的UITextView。
我使用以下代码从属性字符串中提取 URL:
if let attribute = self.textStorage.attribute(NSAttributedString.Key.link, at: characterIndex, effectiveRange: nil){
let url = URL(string: (attribute as AnyObject).debugDescription ?? "");
print("URL: \(url.absoluteString)");
}
这似乎不是获取URL 的有效方法,因为我将属性转换为其调试描述,然后使用它来初始化一个新的URL。
有没有更“官方”的方式从属性中获取URL?
【问题讨论】:
-
attribute类是什么?不是已经是String了吗?那么,如果 let attribute = self.textStorage... as,为什么不做呢?字符串, oras? URL` 如果它已经是一个URL对象。 -
属性是 Any 类型,当我尝试强制转换它时,我得到一个强制转换错误,即使在 print 语句上方设置断点显示属性是“NSURL”类型。有没有更有效的方法从键值存储中获取对象?
-
那么
if let attribute = self.textStorage... as? URL{ print("URL: \(attribute.absoluteString)"); }不行吗?
标签: ios swift url nsattributedstring