UIImageView的触摸事件处理程序

6

我刚开始学习iPhone开发,但似乎找不到我需要的答案。我想要通过编程创建一个UIImageView并为其触摸功能设置事件处理程序。

在C#中,我会有像这样的代码:

Button b = new Button(); b.Click += 我的处理程序代码

现在我有以下代码:

CGRect myImageRect = CGRectMake(0.0f, 0.0f, 141.0f, 151.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];

myImage.userInteractionEnabled = YES;
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; // explicitly opaque for performance
[self.view addSubview:myImage];
[myImage release];

我需要做什么来覆盖触摸事件?

谢谢

7个回答

9

虽然这不是完整的答案,但我认为以下解决方案比“隐形按钮”更好。 只需从UIImageView子类化并覆盖以下方法:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

 //your UIImageView has been touched :)

 //event -> "A UIEvent object representing the event to which the touches belong."

 //touches -> "A set of UITouch instances in the event represented by event that    represent the touches in the UITouchPhaseEnded phase."

}

希望这能帮到您...


真的,这不是我想要的答案。但似乎唯一的方法就是使用继承。我猜c#已经宠坏了我,以至于我认为像这样的方法应该可以在没有那么多工作的情况下使用。无论如何,谢谢。 - madmik3

5

我有一个主视图,其中包含一些图标,比如“关于”图标,用于打开关于视图。 在相应的控制器(mainview)中,我添加了一个touchesBegan事件处理程序。 此外,我需要检查哪个视图已被“触摸”,因为视图上还有更多的图标。 我的UIImageView实例是“aboutImg”,需要检查用户交互(即UI Builder ->视图属性检查器)。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([touch view] == aboutImg){
        [self ShowAbout];
    }
}

确保您勾选了“启用用户交互”。这是最简单的解决方案。


这是最简单的解决方案。我勾选了用户交互复选框,并将其放入子类化的UITableViewCell中,以在单元格中获取多个触摸。完美而简单的工作。无需子类化UIImageView。 - Nick Turner

3

只需使用自定义UIButton,将图像设置为背景图像即可。


0

你不需要使用UIImageView,你可以使用类型为custom的UIButton,并添加touch up inside事件...然后设置button.imageView的setImage方法即可:

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,100,100); //edit for you own frame
UIImage *img = [UIImage imageNamed:@"myimage.png"];
[button setImage:img forState:UIControlStateNormal];

如果你想使用UIImageView,那么你需要为你的图像视图添加手势。否则你可以继承你的UIImageView然后使用触摸事件。


0
最简单的方法是为UIImageView或UIView添加一个轻拍手势识别器,以添加onClick事件。
UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage: myImage];

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action: @selector(onImageViewClicked)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[self.myImageView addGestureRecognizer:singleTap];
[self.myImageView setUserInteractionEnabled:YES];

0
我没有找到使用 UIImageView 直接实现它的方法。但如果您对其进行子类化并重写 nextResponder 方法以返回一个由您控制的委托,则可以实现所需功能。将委托作为子类的属性暴露出来,然后您可以随时传递触摸事件的委托并更改它。

0
我看到其他答案建议在UIImageView下面放置一个不可见的按钮,将图像视图设置为userInteractionEnabled: NO,并让触摸事件传递到按钮。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接