Détecter UIImageView Touch dans Swift

Comment détecter et exécuter une action quand un UIImageView est touché? C'est le code que j'ai jusqu'à présent:

 override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { var touch: UITouch = UITouch() if touch.view == profileImage { println("image touched") } } 

Vous pouvez placer un UITapGestureRecognizer dans votre UIImageView utilisant Interface Builder ou en code (comme vous voulez), je préfère le premier. Ensuite, vous pouvez mettre un @IBAction et gérer le tap dans votre UIImageView , N'oubliez pas de définir le UserInteractionEnabled à true dans Interface Builder ou dans le code.

 @IBAction func imageTapped(sender: AnyObject) { println("Image Tapped.") } 

J'espère que cela t'aidera.

D'accord, j'ai eu ce travail, voici ce que vous devez faire:

 @IBOutlet weak var profileImage: UIImageView! let recognizer = UITapGestureRecognizer() 

Créer une méthode pour vous indiquer quand l'image a été sélectionnée

 func profileImageHasBeenTapped(){ println("image tapped") } 

Super, maintenant dans votre méthode viewDidLoad , écrivez trois lignes de code supplémentaires pour que cela fonctionne

 override func viewDidLoad() { super.viewDidLoad() //sets the user interaction to true, so we can actually track when the image has been tapped profileImage.userInteractionEnabled = true //this is where we add the target, since our method to track the taps is in this class //we can just type "self", and then put our method name in quotes for the action parameter recognizer.addTarget(self, action: "profileImageHasBeenTapped") //finally, this is where we add the gesture recognizer, so it actually functions correctly profileImage.addGestureRecognizer(recognizer) } 

Swift 3

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch:UITouch = touches.first! if touch.view == profileImage { println("image touched") } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch:UITouch = touches.first! if touch.view == profileImage { println("image released") } }