You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift中使用PDFKit实现PDF内容搜索及定位功能

在PDF中搜索字符串并跳转的正确实现方式

我来帮你把搜索和跳转的逻辑串起来~你现在的代码已经用到了关键方法,但没把findString返回的结果和跳转逻辑正确结合,其实findString已经帮你做好了大部分选区的工作,不用手动创建NSRange的选区啦。

核心逻辑梳理

document.findString(_:withOptions:)返回的是[PDFSelection]数组——每个元素都是一处匹配文本的完整选区,包含了该文本所在的页面、位置坐标等所有信息,直接用这个选区就能调用setCurrentSelection完成跳转。

完整代码示例

替换你原来的代码,试试这个:

// 定义你要搜索的目标字符串
let targetString = "你要搜索的内容"

// 执行搜索,获取所有匹配的选区
if let foundSelections = document.findString(targetString, withOptions: .caseInsensitive) {
    if !foundSelections.isEmpty {
        // 跳转到第一个匹配的位置(animate设为true会有平滑滚动效果)
        let firstMatchSelection = foundSelections.first!
        pdfView.setCurrentSelection(firstMatchSelection, animate: true)
        
        // 如果需要支持"下一个/上一个"搜索,可以维护一个索引变量
        // 比如var currentMatchIndex = 0,切换时更新索引再取对应选区:
        // let nextMatch = foundSelections[currentMatchIndex]
        // pdfView.setCurrentSelection(nextMatch, animate: true)
    } else {
        print("没有找到匹配的字符串哦")
    }
}

关键细节说明

  • 你之前用的page?.selection(for: NSRange)是用来手动指定页面上某个范围的文本选区的,适合自定义选中文本的场景,但搜索场景下完全不需要——findString已经帮你生成了所有匹配的合法PDFSelection。
  • setCurrentSelection接受的参数就是PDFSelection类型,传入后会自动帮你定位到对应的页面,并且滚动到文本可见的位置。
  • 记得先判断foundSelections是否为空,避免空数组导致的崩溃。

内容的提问来源于stack exchange,提问作者mrwadepro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:17:49