Search code examples
iosswiftuiimageviewactionuitapgesturerecognizer

iOS Swift: Send action (control event) from subclass of UIImageView


How can I send action (similar kind of tap event) from sub class of UIImageView to View Controller.

Here is reference answer, that I want to apply for UIImageView. (UIImageView does not have UIControl in its super class hierarchy)

Following is my code but not working as I don't know, how to implement, what I need.

class TappableImageView: UIImageView {
  // Initializer methods.....

   //------------------------------------------
    private func addTapGesture(){
        let tapOnImage = UITapGestureRecognizer(target: self, action: #selector(TappableImageView.handleTapGesture(tapGesture:)))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tapOnImage)

    }


    //----------------------------------------------
    @objc func handleTapGesture(tapGesture: UITapGestureRecognizer) {
        // how can I send tap/click event to all view controllers, where I've used this image  from this point. 
    }
}

Is there any alternate/other solution that may work for me?


Solution

  • I will recommend you to use a closure to handle taps:

    class TappableImageView: UIImageView {
    
       var handleTap: (() -> Void)? = nil
    
    
       //------------------------------------------
        private func addTapGesture(){
            let tapOnImage = UITapGestureRecognizer(target: self, action: #selector(TappableImageView.handleTapGesture(tapGesture:)))
            self.isUserInteractionEnabled = true
            self.addGestureRecognizer(tapOnImage)
    
        }
    
    
        //----------------------------------------------
        @objc func handleTapGesture(tapGesture: UITapGestureRecognizer) {
            handleTap?()
        }
    }
    

    And then I your view controller you can use this i.e. in viewDidLoad method:

    override func viewDidLoad() {
        super.viewDidLoad()
        yourTappableImageView.handleTap = { 
           print("an image view was tapped")
        }
    }
    

    It assumes that your TappableImageView is stored in variable named yourTappableImageView.