15

In Swift: I created a simple NSView and now want to execute different functions, depending on which mouseButton is pressed (left or right). how can I detect this?

ixany
  • 5,433
  • 9
  • 41
  • 65

1 Answers1

31

You trap the corresponding mouseDown events

import Cocoa

class MyView : NSView {
    override func mouseDown(theEvent : NSEvent) {
        println("left mouse")
    }

    override func rightMouseDown(theEvent : NSEvent) {
        println("right mouse")
    }
}

See NSResponder for more magic.

Swift 4

import Cocoa

class MyView : NSView {
    override func mouseDown(with theEvent: NSEvent) {
        print("left mouse")
    }

    override func rightMouseDown(with theEvent: NSEvent) {
        print("right mouse")
    }
}
rafaelcpalmeida
  • 874
  • 1
  • 9
  • 28
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • Thanks! But how can I adapt this custom class? Or is it overriding every NSView? I declared the NSView like `let theView = NSView()`. But I think I have to specify that my variable depends to the `MyView`? – ixany Jan 28 '15 at 22:19
  • NSView by itself isn't that useful except as a container for other views. It's one of things you generally subclass to get the behaviour you need . In your case you are detecting left and right clicks and doing something with them. – Warren Burton Jan 28 '15 at 23:51
  • Solved my problem and also... I learned a lot about subclassing. Thank you so much! – ixany Feb 01 '15 at 18:05