繁体   English   中英

在UIScrollView中的UIImageView中检测触摸

[英]Detect touch in UIImageView in UIScrollView

我在UIScrollview中有图像,该图像已添加到View中。
请检查我的代码-

@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不适用于Array中的其他图像
我应该在这里添加什么以检测对阵列的所有图像(第一,第二,...等)的触摸

那是因为您不断更新变量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];

您知道UIScrollview上图像的所有位置,因此可以将scrollView上的位置触摸到数组中的图像位置。 还有一点-绝对不要使用“ ==”比较Objective-C对象,而应始终使用“ isEqual”方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM