An object that manages image data in your app.
you can use UITapGestureRecognizer added to the UIImageView via addGestureRecognizer
snippets:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bannerTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
[iv addGestureRecognizer:singleTap];
[iv setUserInteractionEnabled:YES];
and
- (void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
NSLog(@"%@", [gestureRecognizer view]);
}
Make your image view user interaction enabled in the xib (or through the code if you are adding it programmatically) and use the UIResponder methods touchesBegan, touchesMoved, touchesEnded etc to detect the touch on the image view:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch view] == yourImageView)
{
//add your code for image touch here
}
}
Here I show you two possibilities for achieving that in Swift:
First Possibility
import UIKit
class ViewController: UIViewController {
@IBOutlet var myUIImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// You can also manually set it through IB
// selecting the UIImageView in the storyboard
// and checking "User Interaction Enabled" checkbox
// in the Attributes Inspector panel.
self.myUIImageView.userInteractionEnabled = true
}
// You can choose to use one of the UIResponder methods:
// touchesBegan, touchesMoved, touchesEnded etc, in order to detect the touch
// on the UIImageView.
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch: UITouch? = touches.first
if touch?.view == myUIImageView {
println("myUIImageView has been tapped by the user.")
}
super.touchesEnded(touches, withEvent: event)
}
}
Second Possibility
import UIKit
class ViewController: UIViewController {
@IBOutlet var myUIImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let singleTap = UITapGestureRecognizer(target: self, action: "myUIImageViewTapped:")
singleTap.numberOfTapsRequired = 1 // Initialized to 1 by default
singleTap.numberOfTouchesRequired = 1 // Initialized to 1 by default
self.myUIImageView.addGestureRecognizer(singleTap)
self.myUIImageView.userInteractionEnabled = true
}
func myUIImageViewTapped(recognizer: UITapGestureRecognizer) {
if(recognizer.state == UIGestureRecognizerState.Ended){
println("myUIImageView has been tapped by the user.")
}
}
}
You can also drag and drop a UIButton object over the UIImageView. Then in the storyboard editor, just make the UIButton of Custom type, rendering the UIButton invisible. Then handle the click event just like you would for any button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With