在UIScrollView中检测UIImageView中的触摸

时间:2010-09-21 13:40:12

标签: iphone iphone-sdk-3.0 uiscrollview uiimageview touch

我的UIScrollview中有图像,在视图中添加。
请仔细阅读我的代码 -

@interface ScrollViewController : UIScrollView <UIScrollViewDelegate>{

    UIImageView *productImage;
    UILabel *productName;
    NSArray *productArray;
}
@property(nonatomic,retain) UIImageView *productImage;
@property(nonatomic,retain) UILabel *productName;
@property(nonatomic,retain) NSArray *productArray;

- (id)initWitProducts:(NSArray*)_data;
*.m*

- (id)initWitProducts:(NSArray *)_data
    if ((self = [super init])){
         productArray=[[NSArray alloc]initWithArray:_data];       
         [self setFrame:CGRectMake(0, 0, 320, 480)];
         int countList=[self.productArray count];
         self.contentSize=CGSizeMake(320, 585);


        for(int i=0;i<countList;i++)
        {

            productImage=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[[productArray objectAtIndex:i]objectForKey:@"ProductImage"]]];

            productImage.frame=CGRectMake(95, 35+i*125, 100, 100);
            [productImage setUserInteractionEnabled:YES];
            [self addSubview:productImage];
        }
       return self;     
    }


 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
 {
     if([[touches anyObject]view]==self.productImage)
     NSlog(@"Image Touched");
}

这样做效果很好,但仅适用于阵列中的最后一张图像 touchesBegan不适用于阵列中的其他图像 我应该在这里添加什么来检测阵列的所有图像(第1,第2 ......等)上的触摸

2 个答案:

答案 0 :(得分:0)

您知道UIScrollview上图像的所有位置,因此您可以将scrollView上的位置触摸到阵列中的图像位置。 另一点 - 你不应该使用“==”比较objective-c对象,而是使用“isEqual”方法。

答案 1 :(得分:0)

这是因为您不断更新变量productImage,将代码更改为

   UIImageView *imageInstance=[[UIImageView alloc]initWithImage:[UIImage imageNamed:[[productArray objectAtIndex:i]objectForKey:@"ProductImage"]]];
    imageInstance.frame=CGRectMake(95, 35+i*125, 100, 100);
    [imageInstance setUserInteractionEnabled:YES];
    [self addSubview:imageInstance];