如何使用PDFKit框架突出显示PDFPage中的超链接?

问题描述 投票:0回答:1

我正在使用PDFKit框架,并希望突出显示PDF中所有页面中所有蓝色的超链接。我该怎么办?我已搜索但无法获得足够的相关帖子。

ios swift swift4 ios12
1个回答
1
投票

如果要从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) {

    }
© www.soinside.com 2019 - 2024. All rights reserved.