ios - 有没有办法在点击时存储 pdf 注释?
问题描述
我正在构建一个机器学习应用程序来读取 pdf 的信息,为了训练我需要获取 pdf 注释位置的算法。有没有办法设置手势识别器并在单击时将注释添加到数组中?我在正则表达式上成功地将注释添加到 pdf 中。但是我需要添加注释及其相关信息(单击时在文档中的位置)我可以将手势识别器添加到应用程序吗?我的应用程序使用 SwiftUI。
func makeNSView(context: NSViewRepresentableContext<PDFViewRepresentedView>) -> PDFViewRepresentedView.NSViewType {
let pdfView = PDFView()
let document = PDFDocument(url: url)
let regex = try! NSRegularExpression(pattern: #"[0-9.,]+(,|\.)\d\d"#, options: .caseInsensitive)
let string = document?.string!
let results = regex.matches(in: string!, options: .withoutAnchoringBounds, range: NSRange(0..<(string?.utf16.count)!))
let page = document?.page(at: 0)!
results.forEach { (result) in
let startIndex = result.range.location
let endIndex = result.range.location + result.range.length - 1
let selection = document?.selection(from: page!, atCharacterIndex: startIndex, to: page!, atCharacterIndex: endIndex)
print(selection!.bounds(for: page!))
let pdfAnnotation = PDFAnnotation(bounds: (selection?.bounds(for: page!))!, forType: .square, withProperties: nil)
document?.page(at: 0)?.addAnnotation(pdfAnnotation)
}
pdfView.document = document
return pdfView
}
让水龙头进来
func annotationTapping(_ sender: NSClickGestureRecognizer){
print("------- annotationTapping ------")
}
如果有人通过添加观察者或类似的东西实现了这一点?
谢谢
解决方案
PDFView 已经为注释附加了一个点击手势识别器,因此无需添加另一个。当点击发生时,它将发布PDFViewAnnotationHit
通知。注释对象可以在userInfo
.
makeUIView
在其他任何有意义的地方设置通知的观察者。
NotificationCenter.default.addObserver(forName: .PDFViewAnnotationHit, object: nil, queue: nil) { (notification) in
if let annotation = notification.userInfo?["PDFAnnotationHit"] as? PDFAnnotation {
print(annotation.debugDescription)
}
}
或者更好的是,在您的 SwiftUI 视图中处理通知。
@State private var selectedAnnotation: PDFAnnotation?
var body: some View {
VStack {
Text("Selected Annotation Bounds: \(selectedAnnotation?.bounds.debugDescription ?? "none")")
SomeView()
.onReceive(NotificationCenter.default.publisher(for: .PDFViewAnnotationHit)) { (notification) in
if let annotation = notification.userInfo?["PDFAnnotationHit"] as? PDFAnnotation {
self.selectedAnnotation = annotation
}
}
}
}