如何为PDFAnnotation添加触摸手势?PDFKit自定义注解交互疑问
给PDFKit自定义PDFAnnotation添加触摸交互的方案
因为PDFAnnotation并非UIView子类,没法直接添加手势,这里提供两种可行的实现方式:
方式一:拦截PDFView的触摸事件,判断命中自定义注解
给承载PDF的PDFView添加手势,在回调中把触摸点转换为PDF坐标,再判断是否落在自定义注解的范围内:
// 给PDFView添加点击手势 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handlePDFTap(_:))) pdfView.addGestureRecognizer(tapGesture) @objc private func handlePDFTap(_ gesture: UITapGestureRecognizer) { guard let currentPage = pdfView.currentPage else { return } let touchPoint = gesture.location(in: pdfView) // 转换为PDF坐标系(PDF原点在左下角,和UIKit坐标系相反) let pdfPoint = pdfView.convert(touchPoint, to: currentPage) // 遍历当前页的注解,筛选出自定义注解并判断点击命中 for annotation in currentPage.annotations { guard let customAnnotation = annotation as? CustomPDFAnnotation else { continue } if customAnnotation.bounds.contains(pdfPoint) { // 这里写你的交互逻辑,比如弹出菜单、跳转页面等 print("自定义注解被点击") // 可以给自定义注解加个闭包回调,解耦逻辑 customAnnotation.onTap?() break } } }
方式二:自定义PDFAnnotationView,给视图加手势
利用PDFKit的代理方法,为自定义注解返回对应的PDFAnnotationView子类,直接给视图添加手势:
1. 自定义AnnotationView
class CustomAnnotationView: PDFAnnotationView { override init(annotation: PDFAnnotation, frame: CGRect) { super.init(annotation: annotation, frame: frame) // 添加点击手势 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onAnnotationTap)) addGestureRecognizer(tapGesture) // 根据你的自定义注解样式调整视图外观 backgroundColor = .clear } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func onAnnotationTap() { guard let customAnnotation = annotation as? CustomPDFAnnotation else { return } // 触发交互逻辑 customAnnotation.onTap?() } }
2. 在PDFView代理中返回自定义视图
extension YourViewController: PDFViewDelegate { func pdfView(_ pdfView: PDFView, viewFor annotation: PDFAnnotation) -> PDFAnnotationView? { // 只给自定义注解返回自定义视图 guard annotation is CustomPDFAnnotation else { return nil } return CustomAnnotationView(annotation: annotation, frame: annotation.bounds) } }
注意事项
- 自定义
PDFAnnotation时,要把annotationType设为.custom,这样PDFView才会调用代理方法获取对应的视图; - 方式二更适合复杂交互(比如长按、拖拽),能直接给视图添加多种手势和UI元素;方式一适合简单点击场景,无需额外定义视图类。
内容的提问来源于stack exchange,提问作者kuldeep bhandari
相关产品推荐
相关产品推荐

