0

I create this basic tap gesture function for dismissing view and I added a delegate to override tap when the user taps on another custom sheet (container).

@objc func handleTapGesture() {
    dismiss(animated: true, completion: nil)
}

private func tapGestureToDissmis() {
    let tap = UITapGestureRecognizer()
    tap.addTarget(self, action: #selector(handleTapGesture))
    tap.delegate = self
    view.addGestureRecognizer(tap)
} 

extension TextConfigurationVC : UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    
    if touch.view?.isDescendant(of: container) == true {
        return false
    }
    return true
}

My problem is that I want to implement this for 8 screens and I don't want to repeat my self. i create in my UIViewcontroler extension file this tap function and I don't now how to pass this view :

extension UIViewController : UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    if touch.view?.isDescendant(of: **<UIView>)** == true {
        return false
    }
    return true
}

when I created the global container, each time it was called, it was overlapping each other (tap x 6)

2
  • Is it self.view or simply view (= view controller view you want to dismiss ? In other case you could create a custom II view controller with a default viewDidLoad to initialise the dismiss tap gesture Commented Feb 5, 2022 at 7:33
  • Another way is to add a (computed) var in your extension to store the view. Commented Feb 5, 2022 at 7:35

1 Answer 1

0

Simple way to handle individual tap action for views

   extension UIView {
private struct OnClickHolder {
    static var _closure:()->() = {}
}

private var onClickClosure: () -> () {
    get { return OnClickHolder._closure }
    set { OnClickHolder._closure = newValue }
}

func onTap(closure: @escaping ()->()) {
    self.onClickClosure = closure
    
    isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(onClickAction))
    addGestureRecognizer(tap)
}

@objc private func onClickAction() {
    onClickClosure()
}
}

Usage:

override func viewDidLoad() {
super.viewDidLoad()
let view = UIView(frame: .init(x: 0, y: 0, width: 80, height: 50))
view.backgroundColor  = .red
view.onTap {
    print("View Tapped")
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.