Swift 5 및 iOS 12 UIGestureRecognizerDelegate
에는 gestureRecognizer(_:shouldReceive:)
. gestureRecognizer(_:shouldReceive:)
다음과 같은 선언이 있습니다.
제스처 인식기가 터치를 나타내는 개체를 받아야하는지 대리인에게 문의하십시오.
optional func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
아래의 전체 코드는 gestureRecognizer(_:shouldReceive:)
. 이 코드를 사용하면 ViewController
의 뷰 (포함 imageView
) 의 하위 뷰를 탭 해도 printHello(_:)
메서드가 트리거되지 않습니다 .
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")
}
}
의 대체 구현은 gestureRecognizer(_:shouldReceive:)
다음과 같습니다.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return gestureRecognizer.view === touch.view
}
그러나이 대체 코드 touch.view
는의 하위보기 인지 확인하지 않습니다 gestureRecognizer.view
.