Created
April 9, 2019 13:52
-
-
Save hindalsayyar/6645152ac267ff730c286f7c684598ae to your computer and use it in GitHub Desktop.
Enable Touch for SubView When adding Gesture for parent view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController, UIGestureRecognizerDelegate { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(printHello)) | |
tapGestureRecognizer.delegate = self | |
view.addGestureRecognizer(tapGestureRecognizer) | |
let imageView = UIImageView(image: UIImage(named: "icon")!) | |
imageView.frame = CGRect(x: 50, y: 50, width: 100, height: 100) | |
view.addSubview(imageView) | |
// ⚠️ Enable user interaction for imageView so that it can participate to touch events. | |
// Otherwise, taps on imageView will be forwarded to its superview and managed by it. | |
imageView.isUserInteractionEnabled = true | |
} | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { | |
// Prevent subviews of a specific view to send touch events to the view's gesture recognizers. | |
if let touchedView = touch.view, let gestureView = gestureRecognizer.view, touchedView.isDescendant(of: gestureView), touchedView !== gestureView { | |
return false | |
} | |
return true | |
} | |
@objc func printHello(_ sender: UITapGestureRecognizer) { | |
print("Hello") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment