NSImageView double click action

烈酒焚心 提交于 2019-12-22 03:48:19

问题


I have some NSImageView in my Mac App where the user can drag'n drop objects like .png or .pdf, to store them into User Shared Defaults, that works fine.

I would now like to set an action for when user double click on these NSImageView, but it seems to be a little bit difficult (I had no trouble for NSTableView, but 'setDoubleAction' is not available for NSImage, and tons of answers (here or with google) concerning NSImageView's actions point to making a NSButton instead of NSImageView, so that doesn't help)

Here is part of my AppDelegate.h:

@interface AppDelegate : NSObject <NSApplicationDelegate>{

    (...)

    @property (assign) IBOutlet NSImageView *iconeStatus;

    (...)

@end

and here is part of my AppDelegate.m:

#import "AppDelegate.h"

@implementation AppDelegate

(...)

@synthesize iconeStatus = _iconeStatus;

(...)

- (void)awakeFromNib {

    (...)

[_iconeStatus setTarget:self];
[_iconeStatus setAction:@selector(doubleClick:)];

    (...)

}

(...)

- (void)doubleClick:(id)object {
        //make sound if that works ...
        [[NSSound soundNamed:@"Basso"] play];

}

But that doesn't work.

Can anyone tell me what's the easiest way to do this ?


回答1:


You need to subclass NSImageView and add the following method to your subclass's implementation:

- (void)mouseDown:(NSEvent *)theEvent
{
    NSInteger clickCount = [theEvent clickCount];

    if (clickCount > 1) {
        // User at least double clicked in image view
    }
}



回答2:


Code for Swift 4. Again the NSImageView is subclassed and the mouseDown function is overridden.

class MyImageView: NSImageView {

    override func mouseDown(with event: NSEvent) {
        let clickCount: Int = event.clickCount

        if clickCount > 1 {
            // User at least double clicked in image view
        }
    }

}



回答3:


Another solution using extension:

extension NSImageView {
    override open func mouseDown(with event: NSEvent) {
        // your code here
    }
}

Although this will add that functionality to every NSImageView, so perhaps that's not what you're looking for.



来源:https://stackoverflow.com/questions/13961356/nsimageview-double-click-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!