Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: event when an Imageview is touched

I have an ImageView with a png and I want to do this: when someone touch this imageview it's alpha change to 0.0, is it possible? (all without buttons)

like image 835
cyclingIsBetter Avatar asked Oct 12 '11 12:10

cyclingIsBetter


4 Answers

you can use UITapGestureRecognizer added to the UIImageView via addGestureRecognizer

snippets:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTaped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[iv addGestureRecognizer:singleTap];
[iv setUserInteractionEnabled:YES];

and

- (void)imageTaped:(UIGestureRecognizer *)gestureRecognizer {
    [UIView animateWithDuration:0.5 animations:^(void){
         imageView.alpha = 0.0f;
    }];
}
like image 109
Tek Yin Avatar answered Nov 09 '22 06:11

Tek Yin


Yes, it is possible. For example you can do that with following steps:

  1. set image view's userInteractionEnabled property to YES - so it will receive touch events
  2. add UITapGestureRecongnizer to it
  3. in gesture handler set view's alpha to 0.0, you can do that with animation as well:

    [UIView animateWithDuration:0.5 animations:^(void){
            imageView.alpha = 0.0f;
        }];
    
like image 27
Vladimir Avatar answered Nov 09 '22 06:11

Vladimir


There are already lots of questions like this. Searching with google gave me the following:

touches event handler for UIImageView

UIImageView Touch Event

how can i detect the touch event of an UIImageView

like image 23
Chris Grant Avatar answered Nov 09 '22 05:11

Chris Grant


The code in Swift

In my case I implemented the tap gesture for an image click

1 - Link the image with the ViewController, by drag and drop

@IBOutlet weak var imgCapa: UIImageView!

2 - Instance the UITapGestureRecognizer in ViewDidLoad method:

override func viewDidLoad() {
    super.viewDidLoad()

    //instance the UITapGestureRecognizer and inform the method for the action "imageTapped"
    var tap = UITapGestureRecognizer(target: self, action: "imageTapped")

    //define quantity of taps
    tap.numberOfTapsRequired = 1
    tap.numberOfTouchesRequired = 1

    //set the image to the gesture 
    imgCapa.addGestureRecognizer(tap)
}

3 - Create the method to do what do you want when the image clicked

func imageTapped(){
    //write your specific code for what do you want     

    //in my case I want to show other page by specific segue 
    let sumario = self.storyboard?.instantiateViewControllerWithIdentifier("sumarioViewController") as SumarioViewController

    self.performSegueWithIdentifier("segueSumarioViewController", sender: sumario)
}
like image 39
Weles Avatar answered Nov 09 '22 05:11

Weles