0

我创建了一个照片幻灯片应用程序,其中数组中的图像显示在滚动视图中。我已经向它添加了触摸事件。触摸它应该是 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;
}
4

1 回答 1

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];
}
于 2012-10-30T14:09:47.173 回答