鼠标事件处理程序

时间:2011-05-09 14:26:39

标签: objective-c delegates target-action

MyNSImageView是NSImageView的子类,我在这里:

@interface MyNSImageView : NSImageView 
{
}
@end

@implementation MyNSImageView

//- (void) mouseDown: (NSEvent *) theEvent 
//{
//  do not wish to implement mouseDown event handler from here
//}
@end

在另一个名为MainView的类中,我有:

@interface MainView : NSView 
{
    MyNSImageView *ImageView1;
    MyNSImageView *ImageView2;

}
@end

- (void)awakeFromNib
{
    ImageView1 = [[[MyNSImageView alloc] initWithFrame:NSMakeRect(5, 5, 240, 240)] autorelease];
    NSImage* image1 = [[[NSImage alloc] initWithContentsOfFile: @"/Volumes/MAC DAT2/pictures/MP6107.jpg"] autorelease];
    [ImageView1 setImage:image1];
    [self addSubview:ImageView1];

    ImageView2 = [[[MyNSImageView alloc] initWithFrame:NSMakeRect(300, 5, 240, 240)] autorelease];
    image1 = [[[NSImage alloc] initWithContentsOfFile: @"/Volumes/MAC DAT2/pictures/MP5784.jpg"] autorelease];
    [ImageView2 setImage:image1];
    [self addSubview:ImageView2];
}

- (void) mouseDown2: (NSEvent *) theEvent 
{
    NSLog(@"mousedown2 from MainView");
}
- (void) mouseDown1: (NSEvent *) theEvent 
{
    NSLog(@"mousedown1 from MainView");
}
@end

- (void) mouseDown: (NSEvent *) theEvent 
{
    NSLog(@"mousedown from MainView");
}

在MainView中,当我单击ImageView1或ImageView2时,我希望使用mouseDown1或mouseDown2方法来处理事件而不是mouseDown方法。

我已经阅读过有关目标/操作/委托和响应者的内容,但仍然看不到执行此操作的确切语法。

2 个答案:

答案 0 :(得分:2)

处理此问题的一种方法是使用代理:

首先,为NSImageView子类声明委托协议:

@class MyNSImageView;
@protocol MyNSImageViewDelegate <NSObject>

- (void)myImageView:(MyNSImageView *)view mouseDown:(NSEvent *)event;

@end


@interface MyNSImageView : NSImageView {

}
// declare the delegate member
@property (assign) id<MyNSImageViewDelegate> delegate;
@end

@implementation MyNSImageView
@synthesize delegate = _delegate;

// In your mouseDown method, notify the delegate
- (void)mouseDown:(NSEvent *)event {
    if([self.delegate respondsToSelector:@selector(myImageView:mouseDown:)]) {
        [self.delegate myImageView:self mouseDown:event];
    }
}

@end

然后,声明你的MainView类来实现MyNSImageViewDelegate协议:

@interface MainView : NSView <MyNSImageViewDelegate> {
    MyNSImageView *imageView1;
    MyNSImageView *imageView2;
}
@end

MainView实施中:

- (void)awakeFromNib {
    // create your image views then add our instance as the delegate to each
    ImageView1.delegate = self;
    ImageView2.delegate = self;
}

// here we implement the `MyNSImageViewDelegate` method, which will get 
// called when any `MyImageNSView` instance we've added ourselves as
// delegate to gets clicked.
- (void)myImageView:(MyNSImageView *)view mouseDown:(NSEvent *)event {
    if (view == imageView1) {
        NSLog(@"imageView1 clicked");    
    } else if (view == imageView2) {
        NSLog(@"imageView2 clicked");    
    }
}

答案 1 :(得分:1)

您应该阅读the responder chain。对于要调用的MyCallingClass的-mouseDown:方法,该类的实例必须位于当前响应者链中,并且链中的其他响应者不应处理该事件。