在Swift中检测UIImageView触摸

如何在UIImageView被触摸时检测并执行一个动作? 这是我到目前为止的代码:

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

你可以把UITapGestureRecognizer放在你的UIImageView使用Interface Builder或者代码(如你所愿),我更喜欢第一个。 然后,您可以放入一个@IBAction并在您的UIImageView处理轻敲,不要忘记在Interface Builder或代码中将UserInteractionEnabled设置为true

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

我希望这可以帮助你。

好吧,我得到了这个工作,这是你必须做的:

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

创build一个方法来告诉你什么时候图像被点击

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

太棒了,现在在你的viewDidLoad方法中,写三行代码来实现这个function

 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") } }