获取所选或点击图像的NSMutableArray中的索引

时间:2013-05-14 08:26:32

标签: iphone ios objective-c

我正在开发一个应用程序,我将图像添加到NSMutableArray并在图像视图中显示它们。

我的问题是我不知道如何在我的应用中获取所选图片或点按图片的索引。

FrontsCards=[[NSMutableArray alloc]initWithObjects:@"cloub1.png",@"cloub2.png",@"cloub3.png",@"cloub4.png", nil];

for(int m=0; m< [FrontsCards count];m++)
{
    NSString *imageName=[FrontsCards objectAtIndex:m];

    NSString *fullImageName=[NSString stringWithFormat:@"%@",imageName];

    int padding=25;

    CGRect imageViewFrame=CGRectMake(scrollView.frame.size.width*m+padding, scrollView.frame.origin.y, scrollView.frame.size.width-2*padding, scrollView.frame.size.height);

    ImgView=[[UIImageView alloc]initWithFrame:imageViewFrame];

    [ImgView setImage:[UIImage imageNamed:fullImageName]];

    [ImgView setContentMode:UIViewContentModeScaleAspectFill];


    [scrollView addSubview:ImgView];


    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapImgView:)];
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.delegate = self;

    [self.ImgView addGestureRecognizer:doubleTap];

    self.ImgView.userInteractionEnabled=YES;    
}


CGSize scrollViewSize=CGSizeMake(scrollView.frame.size.width*[FrontsCards count], scrollView.frame.size.height);
[scrollView setContentSize:scrollViewSize];
[self.view addSubview:scrollView];

在点击手势识别器中我应该怎么做以获取图像的索引?

- (void)doubleTapImgView:(UITapGestureRecognizer *)gesture
{
     NSLog(@"double-tap");
}

2 个答案:

答案 0 :(得分:1)

为您使用的每个imageView设置标记,如下所示:

ImgView=[[UIImageView alloc]initWithFrame:imageViewFrame];
ImgView.tag = m;

然后替换此方法:

- (void)doubleTapImgView:(UITapGestureRecognizer *)gesture
{
     NSLog(@"double-tap");
     NSLog(@"%d", gesture.view.tag);
}

它会在 imageView

中打印出图像的索引

答案 1 :(得分:0)

也许你可以使用这样的东西:

first add the name of the image as the accessibilityIdentifier of the the imageview
[imgView setAccessibilityIdentifier:imageName];

然后在tapRecognizer中:

-(void)doubleTapImgView:(UITapGestureRecognizer *)gesture{
    UIImageView *imgView = (UIImageView *)gesture.view;
     int idx = [FrontCards indexOfObject:[imgView accessibilityIdentifier]];
}