Using PDFkit using SwiftUI?

I've seen code to do this using UIkit, but how is this done with SwiftUI?

The PDF's are stored locally in the bundle.

Replies

I would say that you need to use PDFKit view object inside a SwiftUI component like I did to use a TextView in ly SwiftUI app


This is a simplified version :


    import SwiftUI
    import os
    
    let uiLog = OSLog(subsystem: "com.visual-science.CryptiK", category: "UI")


    class  EditorCoordinator : NSObject, NSTextViewDelegate {
      let textView: NSTextView;
      let scrollView : NSScrollView
      let text : Binding<NSAttributedString>
      
      init(binding: Binding<NSAttributedString>) {
        text = binding
        
        textView = NSTextView(frame: .zero)
        textView.autoresizingMask = [.height, .width]
        textView.textStorage?.setAttributedString(text.wrappedValue)
        textView.textColor = NSColor.textColor
     
        scrollView = NSScrollView(frame: .zero)
        scrollView.hasVerticalScroller = true
        scrollView.autohidesScrollers = false
        scrollView.autoresizingMask = [.height, .width]
        scrollView.documentView = textView
        
        super.init()
        textView.delegate = self
      }
      
      func textDidChange(_ notification: Notification) {
        switch  notification.name {
        case NSText.didChangeNotification :
          text.wrappedValue = (notification.object as? NSTextView)?.textStorage ?? NSAttributedString(string: "")
        default:
          os_log(.error, log: uiLog, "Coordinator received unwanted notification")
        }
      }
    
    }
    
    struct DataTextEditorView: View, NSViewRepresentable {
      typealias Coordinator = EditorCoordinator
      typealias NSViewType = NSScrollView
      
      let text : Binding<NSAttributedString>
    
      func makeNSView(context: NSViewRepresentableContext<DataTextEditorView>) -> DataTextEditorView.NSViewType {
        os_log(.info, log: uiLog, "%@", context.coordinator.scrollView)
        return context.coordinator.scrollView
      }
    
      func updateNSView(_ nsView: NSScrollView, context: NSViewRepresentableContext<DataTextEditorView>) {
        os_log(.debug, log: uiLog, "%@", context.coordinator.self)
        os_log(.debug, log: uiLog, "%@", text.wrappedValue)
      }
      
      func makeCoordinator() -> EditorCoordinator {
        os_log(.info, log: uiLog, "makeCoordinator")
        let coordinator =  EditorCoordinator(binding: text)
        return coordinator
      }
      
    }


This is the kind of thing you need to do to use UIKit/AppKit UI element in a SwiftUI based App


Regards


Gerard