如何在UIScrollView中识别来自多个imageView的特定imageView上的触摸?

时间:2011-06-01 21:57:13

标签: iphone objective-c uiimageview touch

我在UIScrollView中有多个ImageView,我想识别我触摸的特定imageView 。这样我就可以做一些动作。 (例如,使用图像名称显示Alert)。

我看过一些类似的帖子,但他们没有正确答案。有些答案对我来说很复杂,因为我对iPhone编程很陌生。

如果有人帮助一个简单的例子,那就太好了。 : - )

我的代码就像这样

- (void)viewDidLoad {   


imgScrollView.userInteractionEnabled =YES;

// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= 5; i++)
{
    NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

    // setup each frame to a default height and width
    CGRect rect = imageView.frame;
    rect.size.height = kHeight;
    rect.size.width = kWidth;
    imageView.frame = rect;
    imageView.tag = i;  

    [imgScrollView addSubview:imageView];

    [imageView release];
}


[self layoutImages];

[super viewDidLoad];
}

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
// WHAT CODE SHOULD I GIVE HERE ?????????? :-)

}

3 个答案:

答案 0 :(得分:3)

我建议您查看UIGestureRecognizer的文档和示例。还有一个更具说明性的Event Handling Guide

这将引导您将手势识别器添加到特定视图(例如您的imageView),可以处理滑动,点按和多点触控手势,无论您喜欢什么。

答案 1 :(得分:1)

您可以使用UIButton代替图片视图。为每个按钮分配标签,然后使用开关(...)识别它们。

答案 2 :(得分:0)

将唯一标记值与每个UIImageView实例相关联:

在viewDidLoad中或初始化图像的位置:

myImageView1.tag = 1;
myImageView2.tag = 2;
myImageView3.tag = 3;

然后尝试手势或类似的东西:

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event       
{
UITouch *touch = [[event allTouches] anyObject];
int t = [touch view].tag;
UIImageView *imageView = (UIImageView *) [self.view  viewWithTag:t];
//your logic here since you have recognized the imageview on which user touched
}

之前没有尝试过类似的东西,但它可能会起作用。