0

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 方法。

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

4

2 回答 2

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");    
    }
}
于 2011-05-11T12:35:37.127 回答
1

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

于 2011-05-11T00:44:59.450 回答