Есть ли способ сохранить аннотацию pdf одним щелчком мыши? - PullRequest
1 голос
/ 13 июля 2020

Я создаю приложение для машинного обучения, чтобы читать информацию о 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 ------")
}

Если кто-то достиг этого, добавив наблюдателя или что-то вроде этого?

Спасибо

1 Ответ

2 голосов
/ 13 июля 2020

К PDFView уже прикреплен распознаватель жестов касания для аннотаций, поэтому нет необходимости добавлять еще один. Когда происходит нажатие, будет опубликовано уведомление sh 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
          }
      }
    }
  }
...