Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 - Adding UITapGestureRecognizer to a subview image - the method is not called

Tags:

ios

swift

I have the following UITapGestureRecognizer setup, but the method is not called?

Note: that the UITapGestureRecognizer is added to a subview item.

Also, it works when adding the UIGestureRecognizerDelegate in SUStepView itself - only problem is that I need it in the container.

class StepViewContainer: NSObject, UIGestureRecognizerDelegate {
var view: SUStepView?

    @objc func tapAction(recognizer: UITapGestureRecognizer) {

    }

    override init(){
        super.init()
        // View
        self.view = Bundle.main.loadNibNamed("SignupV3Views", owner: self, options: nil)![0] as? SUStepView

        let mytapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        mytapGestureRecognizer.numberOfTapsRequired = 1
        self.view?.imageView.addGestureRecognizer(mytapGestureRecognizer)            
    }
}

The view in StepViewContainer:

class SUStepView: UIView {
@IBOutlet weak var imageView: UIImageView!

    @objc public func nextStepTap(sender: UITapGestureRecognizer) {
    }

    override func awakeFromNib() {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(nextStepTap))
        tapGestureRecognizer.numberOfTapsRequired = 1
        self.imageView.addGestureRecognizer(tapGestureRecognizer)

        self.imageView.isUserInteractionEnabled = true
        self.imageView.layer.masksToBounds = true
        self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
        self.imageView.clipsToBounds = true

}
like image 369
Chris G. Avatar asked Oct 05 '17 10:10

Chris G.


1 Answers

Swift 4 Code :

TapGesture :

 tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
 tapGesture.numberOfTapsRequired = 1
 tapGesture.numberOfTouchesRequired = 1

ImageView Tap :

    self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/2.0, height: self.view.frame.size.height/2.0))
    self.imageView.isUserInteractionEnabled = true
    self.imageView.backgroundColor = UIColor.red
    self.imageView.layer.masksToBounds = true
    self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
    self.imageView.clipsToBounds = true
    self.imageView.isUserInteractionEnabled = true
    self.imageView.addGestureRecognizer(tapGesture)
    self.view.addSubview(self.imageView)

Call On Tap

@objc func myviewTapped(_ sender: UITapGestureRecognizer) {
    if self.imageView.backgroundColor == UIColor.yellow {
        self.imageView.backgroundColor = UIColor.green
    }else{
        self.imageView.backgroundColor = UIColor.yellow
    }
}
like image 162
Kirit Modi Avatar answered Oct 17 '22 22:10

Kirit Modi