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

iOS使用PDFKIT实现点击PDF按钮控件触发应用内Safari的问题

实现步骤
  1. 给视图控制器添加PDFViewDelegate代理声明,同时在viewDidLoad中为pdfView绑定代理:
// 类声明示例
class YourViewController: UIViewController, PDFViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad() 
        if let documentURL = Bundle.main.url(forResource: "PDFFileName", withExtension: "pdf"),
                        let document = PDFDocument(url: documentURL),
                        let page = document.page(at: 0) {
                        pdfView?.document = document
                        pdfView?.autoScales = true
                        pdfView?.backgroundColor = UIColor.lightGray
                        // 新增代理绑定
                        pdfView?.delegate = self
                        self.insertLinkButtonInto(page)
        }
    }
}
  1. 完善按钮注解的动作绑定,将你创建的PDFActionURL赋值给注解的action属性:
func insertLinkButtonInto(_ page: PDFPage) {
        let pageBounds = page.bounds(for: .cropBox)
        let linkButtonBounds = CGRect(x: 90, y: pageBounds.size.height - 300, width: 106, height: 32)
        let linkButton = PDFAnnotation(bounds: linkButtonBounds, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
        linkButton.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.button.rawValue)
        linkButton.widgetControlType = .pushButtonControl
        linkButton.caption = "Click link"
        page.addAnnotation(linkButton)
        let linkButtonAction = PDFActionURL(url: URL(string: "https://www.apple.com/")!)
        // 补充动作绑定代码
        linkButton.action = linkButtonAction
}
  1. 实现PDFViewDelegate的链接点击拦截方法,手动唤起应用内Safari:

注意不需要提前全局创建SFSafariViewController,点击时创建即可避免复用异常,同时返回false阻止系统默认跳转到外部浏览器的行为

func pdfView(_ pdfView: PDFView, willClickOn link: URL, at point: CGPoint) -> Bool {
    let sfVC = SFSafariViewController(url: link)
    present(sfVC, animated: true)
    return false
}

如果你需要区分不同链接做不同处理,可以在该方法内判断link的参数值再执行对应逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:39:02