gpt4 book ai didi

macos - 为什么我的 NSView 委托(delegate)方法没有被调用?

转载 作者:行者123 更新时间:2023-12-03 16:51:30 26 4
gpt4 key购买 nike

我正在开发我的第一个 Mac 应用程序,但在让我的 NSView 及其委托(delegate)方法正常工作时遇到了一些问题。我有一个 NSViewController 应该响应鼠标事件,即 mouseDown。这不起作用,相反,我创建了一个自定义 NSView 子类,如下所示:

// Delegate method
@protocol CanvasViewDelegate
- (void)mouseDown:(NSEvent *)event;
@end

@interface CanvasView : NSView
{
id delegate;
}

@property (nonatomic, strong) id delegate;
@end

@implementation CanvasView
@synthesize delegate;

- (void)mouseDown:(NSEvent *)event
{
[delegate mouseDown:event];
}

应充当 NSView 委托(delegate)的 NSViewController 相关部分如下所示:

#import "CanvasView.h"

@interface PaintViewController : NSViewController <CanvasViewDelegate>
{
CanvasView *canvasView;
}

@property (strong) IBOutlet CanvasView *canvasView;

@end

@synthesize canvasView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Initialization code here.
canvasView = [[CanvasView alloc] init];
canvasView.delegate = self;
}

return self;
}

- (void)mouseDown:(NSEvent *)event
{
NSLog(@"Down");
}

现在,mouseDown 方法没有被调用,我做错了什么?

最佳答案

如果您希望 NSView 子类接受事件,则必须实现:

 - (BOOL)acceptsFirstResponder {
return YES;
}

如记录here .

关于macos - 为什么我的 NSView 委托(delegate)方法没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8552011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com