在我的应用程序中,我为每个图像动态创建了imageView,并将它们放在一个scrollview中。 如何通过单击每个图像生成事件以执行导航操作?
答案 0 :(得分:0)
快速且易于实施
UITapGestureRecognizer
UIImageView
使用addGestureRecognizer
。
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[theImageView addGestureRecognizer:singleTap];
[theImageView setUserInteractionEnabled:YES];
现在点击视图时会触发以下内容:
- (void)imageViewTapped:(UIGestureRecognizer *)gestureRecognizer {
NSLog(@"%@", [gestureRecognizer view]);
}
替代解决方案
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[touches anyObject] view] == theImageView)
{
// ImageView tapped.
}
}
答案 1 :(得分:0)
使用UIGestureRecognizer
。在您的情况下,只需在每个UITapGestureRecognizer
上添加UIImageView
即可。 请勿忘记在userInteractionEnabled
上启用UIImageView
,以便考虑点按。
UITapGestureRecognizer* tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewAction:)];
[imageView addGestureRecognizer:tapGR];
imageView.userInteractionEnabled = YES;
-(void)imageViewAction:(UITapGestureRecognizer*)tapGR
{
UIImageView* imageView = tapGR.view;
// Do something with your imageView
}
阅读the Event Handling Guide for iOS (Apple Doc) ,了解有关Gesture识别器如何工作以及如何使用它们的详细信息,以及示例和内容。这本Apple指南非常值得阅读,包含非常有用的概念和解释。