Detect left and right mouse click on NSView
Asked Answered
T

2

17

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?

Trappist answered 28/1, 2015 at 20:22 Comment(0)
P
32

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")
    }
}
Passover answered 28/1, 2015 at 21:25 Comment(3)
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?Trappist
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.Passover
Solved my problem and also... I learned a lot about subclassing. Thank you so much!Trappist
R
0

Don't call super in MouseUp nor MouseDown. It solve my problem.

Reminiscence answered 25/6 at 6:5 Comment(2)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewMaverick
Welcome to StackOverflow. Please, edit and try for How to Answer, describe the effect of what you propose and explain why it helps to solve the problem, make the additional insight more obvious which you contribute beyond existing answers. Consider taking the tour.Ululate

© 2022 - 2024 — McMap. All rights reserved.