触摸事件不起作用?在Imageview?

时间:2009-10-22 11:07:53

标签: iphone

我在viewcontroller.m

的viewdidload中完成了以下操作
    img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
img.multipleTouchEnabled = YES;
[self.view addSubview:img];
[img release];

但Touchbegan,触摸Moved,当我通过Break Point检查时,一切都无法正常工作? 而不是这个,当我使用XIB文件时,我设置了multipleTouchEnabled,但两者都有 触摸事件不起作用... anyHelp?请?

1 个答案:

答案 0 :(得分:3)

您应该尝试设置此属性:

img.userInteractionEnabled = YES;

但这还不够, 因为方法:

– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:

来自UIResponder类(UIVIew的基类),而不是UIViewController。

因此,如果您希望调用它们,则必须定义UIView(或您的UIImageView)的子类,并覆盖基本方法。

示例:

<强> MyImageView.h

@interface MyImageView : UIImageView {
}

@end

<强> MyImageView.m

@implementation MyImageView

- (id)initWithFrame:(CGRect)aRect {
    if (self = [super initWithFrame:rect]) {
        // We set it here directly for convenience
        // As by default for a UIImageView it is set to NO
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // Do what you want here
    NSLog(@"touchesBegan!");
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Do what you want here
    NSLog(@"touchesEnded!");
}

@end

然后,您可以使用视图控制器在示例中实例化MyImageView:

img = [[MyImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[self.view addSubview:img];
[img release];

你应该看到触摸事件(也假设self.view当然将userInteractionEnabled设置为YES)。