how to get the tag of the UIImageView I'm tapping?

前端 未结 3 1364
傲寒
傲寒 2020-12-16 05:29

i have several UIImageView, each of them has a tag; and I have an array of Images, what i want to do is: when user tap one of the UIImageView, the app give back the certain

相关标签:
3条回答
  • 2020-12-16 05:41

    Instead of using a UIImageView why don't you use an UIButton. That way you can simply add a listener for UITouchDown events. You can tag each button so that in your touchDown method you can find which button was pressed.

        UIButton *button = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
        button.backgroundColor = [UIColor blueColor];
        button.tag = i;
        [button addTarget:self action:@selector(touchDown:) controlEvent:UIControlEventTouchDown]; 
    

    And inside of the touchDown: method you simply have to cast the sender to a UIButton in order to access the tag.

    - (void)touchDown:(id)sender
    {
        UIButton* button = (UIButton*)sender;
        switch(button.tag)
        {
            case TAG1:
               break;
            //etc
        }
    }
    
    0 讨论(0)
  • 2020-12-16 05:47

    To find out which image has to be touch ,use touchBegan method:

    Note: First of all you need to confirm about image view should be userIntrectionEnabled=YES; Now use this method:

    -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
        // get touch event
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint touchLocation = [touch locationInView:self.view];
        if ([touch view].tag == 800) {
    
         //if image tag mated then perform this action      
        }
    }
    

    You can use switch statement inside touchBegan.

    0 讨论(0)
  • 2020-12-16 05:56

    At the risk of making a recommendation without seeing the full picture of your app, why not use a custom UIButton instead of UIImageViews for this? With a UIButton you can setup an action and pass the sender id, from which you can easily access your tags and pull the data from your array.

    OR if you really want to use the above code and your know for a fact the - (void)findOutTheTag:(id)sender method is being called, all your have to do is:

    - (void)findOutTheTag:(id)sender {
        switch (((UIGestureRecognizer *)sender).view.tag)      
    {
        case kTag1:
        //...
        case kTag2:
        //...
      }
    }
    
    0 讨论(0)
提交回复
热议问题