0

我使用以下代码将大约 29 个图像添加到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!!!");
}

如您所见,UserInteraction 已启用,一切正常,但代码仅检测来自 UIScrollView 的 Last image 的点击。怎么了?

4

2 回答 2

1

移动线

[imageView setUserInteractionEnabled:YES];

在循环内。在循环完成后,您将仅在最后一张图像上启用用户交互。

于 2013-09-09T02:06:13.583 回答
0

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.

于 2013-09-09T00:42:40.900 回答