2013-12-13 26 views
0

編輯:第一部分已經解決Rubymotion:我如何爲NSView定義一個mouseDown事件?

對不起,我可能noob問題,但我已經搜索了兩天,沒有找到答案。 我已經閱讀了關於事件處理的Objective-C文檔,但是我真的無法將它翻譯成Rubymotion。

我只是試圖在NSView上定義一個包含圖像子視圖的mouseDown事件。

任何提示? 謝謝。

新問題

示例代碼:新的問題更新(查看評論)

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 

回答

0

你的答案是在文檔,但你只是錯過了: )

處理鼠標按下事件由NSView的父類NSResponder處理: https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/mouseDown

您只需要在您的視圖中定義mouseDown。

class MyView < NSView 

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

end 
+0

我已經嘗試過這種方式,但它不工作。也許我錯過了別的東西。 – vash

+0

我更新了第一篇文章 – vash

+0

@vash,你是否正確地繼承了你的視圖,因爲這是正確的方式來做到這一點。你應該檢查你的代碼,因爲你有一個ViewController類繼承自一個NSView ... – siekfried

0

如果使用sugarcube寶石,你可以這樣實現它:

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) 

細節:https://github.com/rubymotion/sugarcube

+0

Sugarxube在osx上不可用。 – siekfried

+0

@siekfried現在支持ios和osx。 – anguskwan

相關問題