I created a button and a NSImageView controls at run time. The button responded to the click event. But the imageview does not. Any suggestions?
NSView *superview = [((MyAppAppDelegate *)[NSApp delegate]).window contentView];
NSButton *button = [ [ NSButton alloc ] initWithFrame: NSMakeRect(300, 50, 50.0, 50.0 ) ];
[superview addSubview:button];
[button setTarget:self];
[button setAction:@selector(button_Clicked:)];
NSImageView *myImageView = [[NSImageView alloc] initWithFrame:NSMakeRect(5, 5, 240, 240)];
NSString* filePath = @"/Volumes/MAC DAT2/pictures/TVX1/153/MP6107frame5786.jpg";
NSImage* image1 = [[NSImage alloc] initWithContentsOfFile:filePath];
[myImageView setImage:image1];
[superview addSubview:myImageView];
[myImageView setTarget:self];
[myImageView setAction:@selector(mouseDown:)];
}
- (IBAction)button_Clicked:(id)sender
{
NSLog(@"button clicked");
}
-(void) mouseDown:(NSEvent *)event
//- (IBAction)mouseDown:(NSEvent *)event //also have tried this one.
{
NSLog(@"mousedown");
}
Edit: I need to use an NSImageView, so using an NSButton with an image is not a solution.
First of all, your code has several memory issues: when you create local objects using
alloc/init, and then hand those objects off to other objects that will retain them, you need to either-releaseor-autoreleasethe objects afterward.NSView‘s-addSubview:inserts the view into the view hierarchy, which is like an array of subviews. As a result,-addSubview:retains the view that you pass in, so you need to autorelease it to counteract your creation using+alloc. When you callNSImageView‘ssetImage:, it retains (or copies) the image you pass in, so you need to autorelease that also to counteract the creation using+alloc.By default,
NSImageViewdoesn’t react to-mouseDown:, or-mouseUp:like otherNSControlsubclasses (namelyNSButton) do. If it works visually, it might make more sense to configure anNSButtonin a way that simply shows an image rather than using anNSImageView, otherwise you’d likely need to create a custom subclass ofNSImageView.In the
NSImageViewsubclass, I would seriously contemplate whether overridingmouseDown:is the proper thing to do, or whether you should wait until you receivemouseUp:to send your action. For example, most buttons do not immediately send their action upon clicking the mouse down; rather, they wait until you let go of the mouse (mouseUp:), in case the user wants to change their mind.In any case, the subclass would look like: