Rubymotion: how can I define a mouseDown event for an NSView?

292 views Asked by At

Edit: this first part has been solved

Sorry for the probably noob question, but I've searched for two days without finding an answer. I've read the Objective-C documentation on event handling but I'm really not able to translate that to Rubymotion.

I am simply trying to define a mouseDown event on an NSView that contains a subview with an image.

Any hint? Thanks.

New issue

EXAMPLE CODE: updated with new issue (look at the comments)

class ViewController < NSView


  def loadWindow
    @window = NSWindow.alloc.initWithContentRect([[400, 500], [480, 200]],
      styleMask: NSTitledWindowMask|NSClosableWindowMask,
      backing: NSBackingStoreBuffered,
      defer: false)
    @window.setTitle("Test")

    @cView = ViewController.alloc.initWithFrame([[400,500], [480, 200]])
    @window.setContentView(@cView)

    @iView = NSImageView.alloc.initWithFrame([[100,100], [30, 30]])
    @iView.setImage(NSImage.imageNamed "Icon")

    @cView.addSubview(@iView)

    @window.orderFrontRegardless
    @window.makeKeyWindow

    @var = "variable"
    puts @var             #   This works and puts "variable"

  end

  def mouseDown(event)
    puts "mouse click"    #   This puts "mouse click"
    puts @var             #   This puts a blank line
  end
end
2

There are 2 answers

5
FluffyJack On BEST ANSWER

Your answer was in the docs, but you just missed it :)

Handling a mouse down event is handled by NSView's parent class NSResponder: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/mouseDown:

You just need to define mouseDown on your view.

class MyView < NSView

  def mouseDown(event)
    # what you want to do
  end

end
2
anguskwan On

if use the sugarcube gem, you can achieve it like this:

button = UIButton.alloc.initWithFrame([0, 0, 10, 10])

button.on(:touch) { my_code }
button.on(:touch_up_outside, :touch_cancel) { |event|
    puts event.inspect
    # my_code...
}

# remove handlers
button.off(:touch, :touch_up_outside, :touch_cancel)
button.off(:all)

detail: https://github.com/rubymotion/sugarcube