1

I'm migrating my macOS app built with SwiftUI 1 to SwiftUI 2. There is a feature that allows user to save the main view as pdf using NSPrinterOperation, which takes an NSView instance.

Currently, the app is on SwiftUI 1 with AppDelegate, and I can get the main view through this code

Button("Print") {
   let appDelegate = NSApp.delegate as! AppDelegate
   let view = appDelegate.window.contentView! // returns the NSHostingView set up in AppDelegate.swift
   ...
   NSPrintOperation(view: view, printInfo: newInfo).run()
}

Since upgrading to SwiftUI2, the AppDelegate is no longer there, and how can I get the view now?

WatashiJ
  • 722
  • 6
  • 19
  • This topic [SwiftUI life-cycle iOS14 Where to put AppDelegate code?](https://stackoverflow.com/a/62538373/12299030) should be helpful. – Asperi Jul 08 '20 at 17:06

1 Answers1

1

See my comment for reference how to set app delegate (which you will be able then access), however also you can content view directly from window via NSApp, like

NSApp.mainWindow?.contentView

or

NSApp.keyWindow?.contentView

depending on your windows configuration.

Asperi
  • 228,894
  • 20
  • 464
  • 690