Alex Germ February 2016

Tap is not recognized on UIImageView Image.

I have a custom UITextField with UIImageView in it. The UITextField should become 'active' after tapping on the UIImageView.

override func drawRect(rect: CGRect) {
    super.drawRect(rect)
    let editView = UIImageView(image: UIImage(named: "pencil-cyan-icon"))
    self.rightViewMode = UITextFieldViewMode.Always
    self.rightView = editView
    editView.frame = CGRectMake(self.frame.width - 50.0, 0, 50.0, self.frame.height)
    editView.userInteractionEnabled = true
    editView.contentMode = UIViewContentMode.Right
    editView.opaque = false
    editView.backgroundColor = UIColor.redColor()
    self.addSubview(editView)

    let tap = UITapGestureRecognizer(target: self, action: "editTextField")
    editView.addGestureRecognizer(tap)     
}

func editTextField() {
    print("didTap")
    self.becomeFirstResponder()
}

Tap works, everything's okay, except one thing. Tap works on the UIImageView, but doesn't work on image that's much smaller(17x17px) than UIImageView. Any ideas why it behave this way?

Answers


dzk February 2016

Actually the problem in your case is that by default, UIImageView doesn't have user interactions enabled.

So add this below your let tap = ...:

editView.userInteractionEnabled = true

That way it works.

Disregard this:

You need to conform your class to UIGestureRecognizerDelegate and add this below the editView.addGestureRecognizer(tap):

tap.delegate = self

Post Status

Asked in February 2016
Viewed 2,304 times
Voted 11
Answered 1 times

Search




Leave an answer