在运行时添加NSImageview不响应mousedown事件

时间:2011-05-08 04:21:54

标签: objective-c cocoa

我在运行时创建了一个按钮和一个NSImageView控件。该按钮响应了click事件。但是imageview没有。有什么建议吗?

    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");

}

修改:我需要使用NSImageView,因此使用带图片的NSButton不是解决方案。

1 个答案:

答案 0 :(得分:8)

首先,您的代码有几个内存问题:当您使用alloc/init创建本地对象,然后将这些对象移交给将保留它们的其他对象时,您需要-release-autorelease之后的对象。

NSView *superview = [((MyAppAppDelegate *)[NSApp delegate]).window contentView];

// memory leak averted:
NSButton *button = [[[NSButton alloc] initWithFrame:
                      NSMakeRect(300, 50, 50.0, 50.0 )] autorelease];

[superview addSubview:button];
[button setTarget:self];
[button setAction:@selector(button_Clicked:)];

// memory leak averted:
NSImageView *myImageView = [[[NSImageView alloc] initWithFrame:
                              NSMakeRect(5, 5, 240, 240)] autorelease];

NSString* filePath = @"/Volumes/MAC DAT2/pictures/TVX1/153/MP6107frame5786.jpg";

// memory leak averted:
NSImage* image1 = [[[NSImage alloc] initWithContentsOfFile:filePath] autorelease];

[myImageView setImage:image1];
[superview addSubview:myImageView];
[myImageView setTarget:self];
[myImageView setAction:@selector(mouseDown:)];

NSView的{​​{1}}将视图插入到视图层次结构中,就像子视图数组一样。因此,-addSubview:会保留您传入的视图,因此您需要使用-addSubview:自动释放它以抵消您的创建。当您致电+alloc的{​​{1}}时,它会保留(或复制)您传入的图片,因此您需要自动发布,以便使用NSImageView来抵消创建。

默认情况下,setImage:不会像其他+alloc子类(即NSImageView)那样对-mouseDown:-mouseUp:做出反应。如果它在视觉上有效,那么以简单地显示图像而不是使用NSControl的方式配置NSButton可能更有意义,否则您可能需要创建{NSButton的自定义子类。 1}}。

NSImageView子类中,我会认真考虑覆盖NSImageView是否正确,或者是否应该等到NSImageView发送您的行动。例如,大多数按钮在单击鼠标时不会立即发送动作;相反,他们等到你放开鼠标(mouseDown:),以防用户想改变主意。

无论如何,子类看起来像:

mouseUp:
相关问题