我的一个控制器有一个NSAttributeString,其中包含一个链接:
@IBOutlet var textView: UITextView!
// Below is extracted from viewDidLoad()
let linkStr = "Click <a href='http://google.com'>here</a> for good times."
let attributedText = try! NSAttributedString(
data: linkStr.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
textView.attributedText = attributedText
我正在为控制器编写单元测试,并且想要验证是否在“此处”文本上放置了正确的链接。(该链接实际上是动态生成的,这就是为什么我要对其进行测试)。
无论如何,我显然可以得到这样的未归因文本:
let text = viewController.textView.attributedText.string
// text == "Click here for good times."
我还可以通过执行以下操作从“这里”获取链接属性:
let url = uviewController.textView.attributedText.attribute(
"NSLink", at: 6, effectiveRange: nil)
// url == A URL object for http://google.com.
问题是我必须对at
参数“ 6”进行硬编码。linkStr
将来的价值可能会改变,因此我不想每次都更新测试。对于这种情况,我们可以假设它始终带有单词“ here”,并带有链接到该单词的链接。
因此,我想做的是找到字符“ here”所在的字符linkStr
,并将该值传递给at
参数,以提取NSLink
属性并验证其是否指向正确的URL。但是我在使如何在Swift中使用字符串范围和索引方面遇到麻烦时遇到了麻烦。
有什么建议么?
这是无需硬编码即可完成的操作。这是基于您的示例的Swift 3操场代码:
import UIKit
import PlaygroundSupport
let linkStr = "Click <a href='http://google.com'>here</a> for good times."
let attributedText = try! NSAttributedString(
data: linkStr.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
attributedText.enumerateAttribute(NSLinkAttributeName , in: NSMakeRange(0, attributedText.length), options: [.longestEffectiveRangeNotRequired]) { value, range, isStop in
if let value = value {
print("\(value) found at \(range.location)")
}
}
该print
语句输出:
http://google.com/ found at 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句