我创建了一个照片幻灯片放映应用程序,其中包含数组中的图像显示在滚动视图中。 我已经为它添加了触摸事件。触摸它应该是UIimageView上触摸图像的详细视图 但我没有通过鼠标点击(我在模拟器上运行它),但我通过alt +鼠标点击得到它 - 当时有两点就像在地图上缩放 我知道这是正确的方法,所以如何在单击鼠标时获得适当的触摸?
添加代码
- (void)viewDidLoad
{
[super viewDidLoad];
scrollView.delegate = self;
scrollView.scrollEnabled = YES;
int scrollWidth = 120;
scrollView.contentSize = CGSizeMake(scrollWidth,80);
int xOffset = 0;
imageView.image = [UIImage imageNamed:[imagesName objectAtIndex:0]];
for(int index=0; index < [imagesName count]; index++)
{
UIImageView *img = [[UIImageView alloc] init];
img.bounds = CGRectMake(10, 10, 50, 50);
img.frame = CGRectMake(5+xOffset, 0, 160, 110);
NSLog(@"image: %@",[imagesName objectAtIndex:index]);
img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
[images insertObject:img atIndex:index];
scrollView.contentSize = CGSizeMake(scrollWidth+xOffset,110);
[scrollView addSubview:[images objectAtIndex:index]];
xOffset += 170;
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.nextResponder touchesBegan:touches withEvent:event];
UITouch * touch = [[event allTouches] anyObject];
for(int index=0;index<[images count];index++)
{
UIImageView *imgView = [images objectAtIndex:index];
NSLog(@"x=%f,y=%f,width=%f,height=%f",
imgView.frame.origin.x,imgView.frame.origin.y,
imgView.frame.size.width,imgView.frame.size.height);
NSLog(@"x= %f,y=%f",[touch locationInView:self.view].x,[touch
locationInView:self.view].y) ;
if(CGRectContainsPoint([imgView frame], [touch locationInView:scrollView]))
{
[self ShowDetailView:imgView];
break;
}
}
}
-(void)ShowDetailView:(UIImageView *)imgView
{
imageView.image = imgView.image;
}
答案 0 :(得分:0)
我不会在touchesBegan:
方法中自行执行所有命中测试,而是高度推荐使用UITapGestureRecognizer
。像这样修改你的代码:
- (void)viewDidLoad
{
//...
for(int index=0; index < [imagesName count]; index++)
{
UIImageView *img = [[UIImageView alloc] init];
img.bounds = CGRectMake(10, 10, 50, 50);
img.frame = CGRectMake(5+xOffset, 0, 160, 110);
NSLog(@"image: %@",[imagesName objectAtIndex:index]);
img.image = [UIImage imageNamed:[imagesName objectAtIndex:index]];
[images insertObject:img atIndex:index];
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]
[img addGestureRecognizer:tapGR];
img.userInteractionEnabled = YES;
/...
}
}
- (void)handleTap:(UIGestureRecognizer *)sender
{
UIImageView *iv = sender.view;
[self ShowDetailView:iv];
}