在Swift中进行macOS打印 [英] macOS Printing in Swift

查看:54
本文介绍了在Swift中进行macOS打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这不是iOS问题.

Please note this is not an iOS question.

我有一个基于NSView的应用程序(即不是基于文档的),我想使用打印子系统.我可以在主控制器中获取NSViews以进行打印.但是,我希望有一个仅用于打印的特殊视图.该视图不应显示在应用程序的窗口中.该视图包含两个NSTextField,两个NSTextView和5个标签.

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. 将 NSView 添加到我的主视图窗口?似乎合乎逻辑,但在情节提要中很尴尬(我无法将视图放置在情节提要中).

  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).

使用xib以编程方式创建自定义NSView?

Programmatically create a custom NSView with a xib?

为此,我尝试了:

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

这会导致全面的致命错误:在解包可选值时意外发现 nil"消息.

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

插座配置正确(我认为)

The outlets are configured correctly (I think)

  1. 单独的ViewController?如果是这样,如何避免有两个打印按钮-一个用来调用打印控制器,另一个用来打印PrintController的视图.

我尝试阅读Apple文档,但是这并不是我学得最好的方法.我发现Swift中也没有打印文档.我曾经历过很多SE问题,但还是空白.您能给我指出解决方案吗?

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.

推荐答案

我认为这里的具体问题是您永远不会导致加载视图.

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

您可以通过重写控制器上的 viewDidLoad 方法来再次检查是否存在这种情况.如果从未调用过,则永远不会从笔尖加载视图.

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.

通常,当您显示视图控制器时,UI机制会处理所有这一切,这就是为什么当它不发生时它会如此令人困惑的原因.

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.

您应该能够通过访问控制器上的view属性来触发视图加载.例如

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 有一些附加信息.

您也可以直接调用 loadView(),尽管通常对此并不满意.

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

这篇关于在Swift中进行macOS打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆