如何使用标记分配和使用imageViews数组

时间:2016-05-13 10:31:25

标签: ios objective-c xcode

我以编程方式在UIScrollView中创建了imageViews数组,然后通过为用户分配点击手势进行交互。现在,我想区分,单击哪个图像视图,以便我可以从点击的imageView获取图像。但是,我无法为它们分配不同的标签。这是我的代码。我正在添加15张图片。

for (int i = 0; i < 15; i++) {
        originx = ((_imageView.frame.size.width+5)*i); //Calculate origin x for each image view.

    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(originx, self.view.frame.origin.y+5, imageViewHeightWidth, imageViewHeightWidth)];

    [_imageView setBackgroundColor:[ UIColor colorWithRed:191.0/255.0 green:65.0/255.0 blue:78.0/255.0 alpha:0.5]];
    //_imageView.layer.cornerRadius = 10.0;
    _imageView.image = [UIImage imageNamed:[_imgArray objectAtIndex:i]];

    //Enabling user interaction for gesture.
    [_imageView setUserInteractionEnabled:YES];
    [_imageView setMultipleTouchEnabled:YES];

    //Tap Gesture enabled.
    _gesture =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTheImage:)];
    _gesture.numberOfTapsRequired = 1;

    //Add a tap gesture.
    [_imageView addGestureRecognizer:_gesture];

    //Assigning the tag to image View.
    _imageView.tag = 200+i;

    //Adding image in to scroll view.
    [_gallaryScrollView addSubview:_imageView];    
}

 //Here i am getting same tag value for every imageView. i.e. "214".
-(void)tapTheImage:(id)sender
{
    NSLog(@"The tag value of imagView is%ld",(long)[_imageView tag]);
}

2 个答案:

答案 0 :(得分:3)

更改TapTheImage方法

-(void) TapTheImage:(UITapGestureRecognizer *)gestureRecognizer{

    //Get the View
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSLog(@"%d",tableGridImage.tag);
}

答案 1 :(得分:0)

您没有创建UIImageView的新对象。 改变行

_imageView = [[UIImageView alloc]initWithFrame:CGRectMake(originx, self.view.frame.origin.y+5, imageViewHeightWidth, imageViewHeightWidth)];

UIImageView *_imageView = [[UIImageView alloc]initWithFrame:CGRectMake(originx, self.view.frame.origin.y+5, imageViewHeightWidth, imageViewHeightWidth)];