Hope
Hope

Reputation: 2326

Drawing at Cocoa with Swift Creates an error

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 
  }
}

then we connected the class to a NSView like this

enter image description here

But we have received

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

Besides the print(" drawRect is executed ") was not executed.

Most probably we are forgetting something simple.

Upvotes: 2

Views: 190

Answers (1)

Eric Aya
Eric Aya

Reputation: 70097

Your class inherits from NSView:

class DrawImageHolder: NSView

So the print you're using:

print(" drawRect is executed  ")

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.

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  ")
  }
}

Upvotes: 1

Related Questions