Skip to content

Instantly share code, notes, and snippets.

@KosmicTask
Created April 7, 2014 15:31
Show Gist options
  • Save KosmicTask/10022512 to your computer and use it in GitHub Desktop.
Save KosmicTask/10022512 to your computer and use it in GitHub Desktop.
NSImageView subclass that responds to mouse up and sends click event
@interface BPImageView : NSImageView
@property SEL clickAction;
@end
@implementation BPImageView
- (void)mouseDown:(NSEvent *)theEvent
{
// see
// http://www.cocoabuilder.com/archive/cocoa/115981-nsimageview-subclass-and-mouseup.html
if (theEvent.type != NSLeftMouseDown) {
[super mouseDown:theEvent];
}
}
- (void)mouseUp:(NSEvent *)theEvent
{
if (theEvent.type == NSLeftMouseUp) {
NSPoint pt = [self convertPoint:[theEvent locationInWindow] fromView:nil];
if (NSPointInRect(pt, self.bounds)) {
[NSApp sendAction:self.clickAction to:self.target from:self];
}
} else {
// this should never be called, but...
[super mouseUp:theEvent];
}
}
@end
@markrickert
Copy link

Thanks for this!

I added this to make sure mouse events weren't firing on an image that wasn't visible:

if (NSPointInRect(pt, self.bounds) && self.alphaValue > 0.0) {
}

@wanderingstan
Copy link

Pardon a dumb question, but where/how does one capture the sent click event? Should I be creating a clickAction method somewhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment