我在运行时创建了一个按钮和一个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");
}
Run Code Online (Sandbox Code Playgroud)
编辑:我需要使用NSImageView,所以使用NSButton带图像不是解决方案.
首先,您的代码有几个内存问题:当您使用创建本地对象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:)];
Run Code Online (Sandbox Code Playgroud)
NSView的-addSubview:插入视图到视图的层次结构,它就像子视图的阵列.因此,-addSubview:保留您传入的视图,因此您需要自动使用它来抵消您的创建+alloc.当你打电话NSImageView的setImage:,它保留(或复制)的图像传递的,所以你需要自动释放也使用以抵消创作+alloc.
默认情况下,NSImageView不响应-mouseDown:,或-mouseUp:像其他NSControl子类(即NSButton)那样做.如果它在视觉上有效,那么配置一个NSButton简单地显示图像而不是使用a的方式可能更有意义NSImageView,否则你可能需要创建一个自定义子类NSImageView.
在NSImageView子类中,我会认真思考覆盖是否mouseDown:是正确的事情,或者是否应该等到你收到mouseUp:发送你的行动.例如,大多数按钮在单击鼠标时不会立即发送动作; 相反,他们等到你放开鼠标(mouseUp:),以防用户想要改变主意.
在任何情况下,子类看起来像:
@interface MDImageView : NSImageView {
}
@end
@implementation MDImageView
- (void)mouseUp:(NSEvent *)event {
if ([[self target] respondsToSelector:[self action]]) {
[NSApp sendAction:[self action] to:[self target] from:self];
}
}
@end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3243 次 |
| 最近记录: |