Believe2014
Believe2014

Reputation: 3964

How does the `tap` function get ignored?

Following Apple's Guide to build a MealKeeper app, I was able to create a text field and an image view. After dragging and dropping the UITapGestureRecognizer on top of the image view, I added the code to hide the keyboard by making the text field to resign. MealKeeper

When I run this code in simulator, I first click on the text field, the keyboard appears. Then I click on the image view, the keyboard does not get hide.

How does the tap function get ignored?

Upvotes: 2

Views: 50

Answers (4)

Edison
Edison

Reputation: 11987

Syntax is a bit different in the latest Swift 2.3

class ViewController: UIViewController {

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var imageView: UIImageView!
@IBAction func tap(sender: UITapGestureRecognizer) {
    textField.resignFirstResponder()
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(ViewController.tap(_:)))
    imageView.userInteractionEnabled = true
    imageView.addGestureRecognizer(tapGestureRecognizer)
}
}

Upvotes: 0

Believe2014
Believe2014

Reputation: 3964

For learners who rely on the IDE to fix this issue, you need to enable the image view's user interaction.

enter image description here

Upvotes: 1

Amir iDev
Amir iDev

Reputation: 1257

You can add touch delegates and resign text field keyboard on that.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
if(touch.phase == UITouchPhaseBegan) {
    [self.myTextField resignFirstResponder];
}

}

Upvotes: 0

JingJingTao
JingJingTao

Reputation: 1790

You need to add the gesture to you imageview, create an IBOutlet to your imageview and add the following to 'viewDidLoad'.

let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("tap:"))
imageView.userInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)

Good luck.

Upvotes: 2

Related Questions