使用Swift在Cocoa上绘制会产生错误 [英] Drawing at Cocoa with Swift Creates an error
问题描述
当尝试像在iOS应用程序中一样绘制时,我们遇到了一个问题。经过数小时的搜索,没有运气,我们决定在这里询问。
When trying to draw just like in an iOS application we faced a problem. After hours of search with no luck, we decided to ask here.
要制作绘图,我们创建了一个类
To make a drawing we created a class as
import Cocoa
class DrawImageHolder: NSView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
print(" drawRect is executed ")
// drawing code
}
}
然后我们将类连接到 NSView
这样
then we connected the class to a NSView
like this
但是我们已经收到
-[NSApplication runModalForWindow:]可能不会在事务提交内部调用(通常这意味着它是在
视图的-drawRect:方法内部调用的。)模态对话框已被抑制为
避免死锁。
-[NSApplication runModalForWindow:] may not be invoked inside of transaction commit (usually this means it was invoked inside of a view's -drawRect: method.) The modal dialog has been suppressed to avoid deadlock.
从控制台而不是绘图发出消息。
message from console instead of drawing.
除了未执行print( drawRect被执行)。
Besides the print(" drawRect is executed ") was not executed.
很可能我们忘记了一些简单的东西。
Most probably we are forgetting something simple.
推荐答案
您的类继承自NSView:
Your class inherits from NSView:
class DrawImageHolder: NSView
因此,您使用的 print
:
print(" drawRect is executed ")
实际上是 NSView
' s print
。该视图试图显示一个用于打印的对话框,并根据错误状态从不该显示的位置开始显示该对话框。
is actually NSView
's print
. The view tries to show a dialog for printing, and as the error states, it does from a place it shouldn't.
解决方案是在前缀 print
和 Swift
,以便您显式使用Swift的 print
而不是 NSView
的打印
:
The solution is to prefix print
with Swift
so that you're explicitly using Swift's print
instead of NSView
's print
:
class DrawImageHolder: NSView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
Swift.print(" drawRect is executed ")
}
}
这篇关于使用Swift在Cocoa上绘制会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!