SwiftUI on macOS: PDF Help book source code
This is the Swift source code to accompany the article SwiftUI on macOS: PDF Help book.
LittleHelperApp.swift
import SwiftUI
@main
struct LittleHelperApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
Window(“Help Window”, id: “help”) {
HelpView()
}
.commands {
HelpCommands()
}
}
}
MenuCommands.swift
import SwiftUI
struct HelpCommands: Commands {
@Environment(.openWindow) var openWindow
var body: some Commands {
CommandGroup(replacing: .help) {
Button(“LittleHelper Help”, action: showHelpWindow)
}
}
func showHelpWindow() {
openWindow(id: “help”)
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: “globe”)
.imageScale(.large)
.foregroundStyle(.tint)
Text(“Hello, world!”)
}
.padding()
}
}
#Preview {
ContentView()
}
HelpView.swift
import SwiftUI
import Quartz
struct PDFKitView: NSViewRepresentable {
typealias NSViewType = PDFView
let url: URL // new variable to get the URL of the document
func makeNSView(context: NSViewRepresentableContext<PDFKitView>) -> PDFView {
// Creating a new PDFVIew and adding a document to it
let pdfView = PDFView()
pdfView.document = PDFDocument(url: self.url)
pdfView.autoScales = true
pdfView.displayMode = .singlePage
return pdfView
}
func updateNSView(_ uiView: PDFView, context: NSViewRepresentableContext<PDFKitView>) {
// we will leave this empty as we don’t need to update the PDF
}
}
struct HelpView: View {
let pdfUrl = Bundle.main.url(forResource: “LittleHelperHelp”, withExtension: “pdf”)!
var body: some View {
PDFKitView(url: pdfUrl)
}
}
#Preview {
HelpView()
}
End of code supplement.