macOS Printing in Swift

自闭症网瘾萝莉.ら 提交于 2021-02-10 14:31:14

问题


Please note this is not an iOS question.

I have an NSView-based app (i.e. not document-based), and I’d like to bolt on a printing subsystem. I can get NSViews in my main controller to print ok. However, I want to have a special view constructed just for printing. The view should not show in the app’s window. The view contains two NSTextFields, two NSTextViews, and 5 labels.

I cannot seem to figure out a way to do this. I have tried various forms of these examples:

  1. Add an NSView to my main view window? Seems logical, but it’s awkward in a storyboard, (I can’t position the view in the storyboard).

  2. Programmatically create a custom NSView with a xib?

For this, I’ve tried:

@IBOutlet weak var printView: NSView!
….
let printOperation = NSPrintOperation(view: printView!)

This results in the comprehensive "fatal error: unexpectedly found nil while unwrapping an Optional value” message.

The outlets are configured correctly (I think)

  1. A seperate ViewController? If so, how can I avoid having two print buttons — one to call the print controller, and the second, to print the PrintController’s view.

I’ve tried reading the Apple docs, but they are not the way I learn best. There are also no Print documents in Swift that I've found. I’ve waded through many SE questions, but have come up blank. Could you point me towards a solution please.


回答1:


I think the specific problem here is that you're never causing the view to be loaded.

You can double check whether this is the case by overriding the viewDidLoad method on the controller. If it's never called, your view is never loaded from the nib.

Normally the UI machinery takes care of all that when you display a view controller, which is why it can be so confusing when it doesn't happen.

You should be able to trigger the view load by accessing the view property on the controller. e.g.

_ = self.view // Touch the view to force it to load

https://developer.apple.com/documentation/appkit/nsviewcontroller/1434401-view has some additional information.

You can also call loadView() directly although that's usually frowned upon.



来源:https://stackoverflow.com/questions/42930873/macos-printing-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!