我正在开发我的第一个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没有被调用,我做错了什么?
答案 0 :(得分:5)
答案 1 :(得分:1)
以编程方式创建视图,但确实有效。像这样:
NSRect canvasRect = self.view.frame;
canvasView = [[CanvasView alloc] initWithFrame:canvasRect];
[self.view addSubview:canvasView];
canvasView.delegate = self;