S.Basnagoda
S.Basnagoda

Reputation: 711

UITapGestureRecognizer not working with custom view class

UITapGestureRecognizer works perfectly fine in code 1. tapAction is called as expected. However it's not working in code 2. Can somebody please tell me what's wrong in code 2?

(This and this are quite similar questions, but still couldn't figure it out) 🧐

Code 1:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        myView.backgroundColor = .red
        myView.addGestureRecognizer( UITapGestureRecognizer(target:self,action:#selector(self.tapAction)) )

        self.view.addSubview(myView)
    }

    @objc func tapAction() {
        print("tapped")
    }
}

Code 2:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let myView = MyView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        self.view.addSubview(myView)
    }
}

class MyView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func initView(){
        let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        myView.backgroundColor = .red
        myView.addGestureRecognizer(UITapGestureRecognizer(target:self,action:#selector(self.doSomethingOnTap)))
        addSubview(myView)
    }

    @objc func doSomethingOnTap() {
        print("tapped")
    }
}

Upvotes: 0

Views: 791

Answers (1)

Rico Crescenzio
Rico Crescenzio

Reputation: 4226

You're creating a subview that in this particular case goes out of the parent bounds because the view main view has 100 height and 100 width and the subview is placed at x: 100 and y: 100, resulting to be positioned at the exact end of the parent.

The subview you create in initView should have (x: 0, y: 0) origin.

Upvotes: 1

Related Questions