我正在使用PDFKit框架,并希望突出显示PDF中所有页面中所有蓝色的超链接。我该怎么办?我已搜索但无法获得足够的相关帖子。
如果要从pdf中提取所有链接,请应用正则表达式并提取数组中的所有链接,如:
let text = pdfView.document?.string ?? ""
let types: NSTextCheckingResult.CheckingType = .link
do {
let detector = try NSDataDetector(types: types.rawValue)
let matchResult = detector.matches(in: text, options: .reportCompletion, range: NSRange(location: 0, length: text.count))
let linksArray: [URL] = matchResult.compactMap({ $0.url })
print("List of available links: \(linksArray)")
} catch (let error) {
print (error.localizedDescription)
}
但是,如果您只想突出显示链接并单击其中的操作,那么PDFKit
确实有一个属性enableDataDetectors
来检测PDFView
中的链接。你必须启用它。
根据苹果文档:
打开或关闭数据检测。如果启用,将在页面变为可见时扫描页面文本以查找URL。找到URL的地方,就会创建链接注释。这些是临时注释,不会保存。
您可以将其用作:
let pdfView = PDFView.init(frame: self.view.bounds)
pdfView.enableDataDetectors = true
如果你需要处理这个链接的点击,然后符合PDFViewDelegate
,它将调用委托方法:
func pdfViewWillClick(onLink sender: PDFView, with url: URL) {
}