1

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.

ICL1901
  • 7,632
  • 14
  • 90
  • 138
  • 1
    Related: http://stackoverflow.com/a/29375748/2227743 – Eric Aya Mar 21 '17 at 15:26
  • Thanks Eric. That helps, however, what if I need a slightly more complex layout (half a dozen fields and labels)? I should have said that in my question. – ICL1901 Mar 21 '17 at 15:45
  • You're welcome, unfortunately I can't help further, my knowledge about printing on a Mac stops there. Let's hope someone will find a solution. And sure, please add all the necessary details in your question. :) – Eric Aya Mar 21 '17 at 15:49
  • Will do, and thanks again. – ICL1901 Mar 21 '17 at 15:51

1 Answers1

2

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.

Cole
  • 103
  • 6