为什么不调用我的NSView委托方法?

时间:2011-12-18 13:27:09

标签: macos cocoa delegates nsview

我正在开发我的第一个Mac应用程序,我在使用NSView及其委托方法时遇到了一些麻烦。我有一个应该响应鼠标事件的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委托的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没有被调用,我做错了什么?

2 个答案:

答案 0 :(得分:5)

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

 - (BOOL)acceptsFirstResponder {
     return YES;
 }

记录在案here

答案 1 :(得分:1)

以编程方式创建视图,但确实有效。像这样:

NSRect canvasRect = self.view.frame;
canvasView = [[CanvasView alloc] initWithFrame:canvasRect];
[self.view addSubview:canvasView];
canvasView.delegate = self;