8

I know how to implement touchesBegan for UIImageView

is it possible to implement UITouchDown for UIImageView ?(i know that i can use touchesBegan instead of UITouchDown but i want to implement UITouchDown)

etolstoy
  • 1,798
  • 21
  • 33

4 Answers4

13

Use a UIButton.

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setImage:someUIImage forState:UIControlStateNormal];
[aButton addTarget:self action:@selector(aMethod) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:aButton];

Alternative to UIButton (longer method)

A UIControl implements user interactions and support for fine-grained user interactions already. You can combine the functionality of a UIImageView and a UIControl to achieve this since both are subclasses of UIView.

To get this behavior, add an object of UIImageView as a subview to a UIControl such that the image is fully covered. Then add a event handler to this control using addTarget:action:forControlEvents:. Here's an example:

// assuming the image view object exists
UIImageView *anImageView = ..;

// create a mask that the covers the image exactly
UIControl *mask = [[UIControl alloc] initWithFrame:anImageView.frame];

// add the image as a subview of this mask
CGSize imageSize = anImageView.frame.size;
anImageView.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
[mask addSubview:anImageView];

// add a target-action for the desired control events to this mask
[mask addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];

// add the mask as a subview instead of the image
[self.view addSubview:mask];
Martin Metselaar
  • 347
  • 1
  • 2
  • 11
Anurag
  • 140,337
  • 36
  • 221
  • 257
2

You can use UITapGestureRecognizer, instead of creating custom UIButton.

etolstoy
  • 1,798
  • 21
  • 33
Yariv Nissim
  • 13,273
  • 1
  • 38
  • 44
1

You can't.

control events such as UIControlEventTouchDown etc are available for UIControl's child objects like UIButton, UITextField etc. UIImageView is a UIView and hence cannot generate control notifications.

You have to use touchesBegan and co.

etolstoy
  • 1,798
  • 21
  • 33
Swapnil Luktuke
  • 10,385
  • 2
  • 35
  • 58
0

control events such as UIControlEventTouchDown etc are available for UIControl's child objects like UIButton, UITextField etc. UIImageView is a UIView and hence cannot generate control notifications.