Reputation: 317
I use the following code to add about 29 image to UIScrollView
.
- (void)setupHorizontalScrollView
{
_scrollViewEffects.delegate = self;
[_scrollViewEffects setCanCancelContentTouches:NO];
_scrollViewEffects.clipsToBounds = NO;
_scrollViewEffects.scrollEnabled = YES;
_scrollViewEffects.pagingEnabled = YES;
NSUInteger nimages = 0;
NSInteger tot=0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:@"e%d.png", nimages];
UIImage *imageThumb = [UIImage imageNamed:imageName];
[imageView setTag:nimages];
if (tot==29) {
break;
}
if (4==nimages) {
nimages=0;
}
imageView = [[UIImageView alloc] initWithImage:imageThumb];
UITapGestureRecognizer *singleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSingleTap:)];
singleTap.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:singleTap];
CGRect rect = imageView.frame;
rect.size.height = 50;
rect.size.width = 50;
rect.origin.x = cx;
rect.origin.y = 0;
imageView.layer.borderColor = [UIColor whiteColor].CGColor;
imageView.layer.borderWidth = 1;
imageView.frame = rect;
[_scrollViewEffects addSubview:imageView];
cx += imageView.frame.size.width+5;
tot++;
}
//self.pageControl.numberOfPages = nimages;
[_scrollViewEffects setContentSize:CGSizeMake(cx, [_scrollViewEffects bounds].size.height)];
[imageView setUserInteractionEnabled:YES];
}
- (void)handleSingleTap:(UIGestureRecognizer *)sender
{
NSLog(@"image tapped!!!");
}
As you can see, UserInteraction is Enabled, everything works, But the code detects taps only for Last image from UIScrollView. What is wrong?
Upvotes: 0
Views: 75
Reputation: 62676
Move the line
[imageView setUserInteractionEnabled:YES];
to be inside the loop. You're setting user interaction enabled on only the last image, after the loop is complete.
Upvotes: 1
Reputation: 39081
You are creating only 1 instance of the imageView. To fix your problem you have to create a new instance for eatch imageView:
for (int a = 0; a < 5; a++) {
UIIMageVIew *imgView = [[UIIMageView alloc] init];
[self.view addSubview:imgView];
}
This will create 5 UIIMageView
instances.
The difference here is that a new instance is added 5 times and in your code atm is adding the same instance so when you add them they will not "exist" and only the last one will.
And to improve your for loop set it up like I did here but put 29 instead, it'll make your code cleaner and shorter.
Upvotes: 0