0

我正在尝试使用一组可点击的 UIImageView 创建一个滚动视图。我的目标是,当单击 ImageView 时,它会返回它在数组中占据的位置。问题是我不知道如何“抓住”职位的号码。我怎么做?

到目前为止,我有:

- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer {

    NSLog(@"%@",)//here is where i want to return the element's position.
}

-(void) preenchemenu {

    [menu setContentSize:CGSizeMake(400, 91)];
    int x=0;
    imagensmenu=[NSArray arrayWithObjects:[UIImage imageNamed:@"teste2.tiff"],[UIImage    imageNamed:@"teste2.tiff"], nil];

    for (int i = 0; i <3; i++) {

        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x,0 , 90, 91)];
        x=x+90;
        imageView.image = [imagensmenu objectAtIndex:i];
        imageView.tag = 1000+ i;
        imageView.userInteractionEnabled = YES;
        imageView.multipleTouchEnabled = YES;
        UITapGestureRecognizer *tapRecognizermenu = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(respondToTapGesture:)];
        tapRecognizermenu.numberOfTapsRequired = 1;

        [imageView addGestureRecognizer:tapRecognizermenu];
        [menu addSubview:imageView];
    }
}
4

2 回答 2

1

您可以创建一个数组来保存您的 imageView,然后在点击它时找到您的 imageView 在此数组中的位置。

为此添加属性

@property (nonatomic, strong) NSMutableArray *imageViews;

在init中初始化它

- (id)init...
{
  self = [super init...
  if (self) {
    _imageViews = [NSMutableArray array];
  }
  return self;
}

然后稍微修改您当前的方法,将 imageViews 以及菜单的子视图添加到此数组中

[self.imageViews addObject:imageView];
[menu addSubview:imageView];

然后在你的手势识别器回调中你可以做

- (void)respondToTapGesture:(id)sender;
{
  UIView *view = [sender view];
  NSLog(@"%d", [self.imageViews indexOfObject:view]);
}
于 2013-03-11T15:05:42.010 回答
0

只需找到索引

- (IBAction)respondToTapGesture:(UITapGestureRecognizer *)recognizer
{
  UIView *view = recognizer.view;
  NSLog(@"Index of image in array is %d", view.tag-1000);
}
于 2013-03-11T17:17:39.493 回答