Reputation: 3964
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.
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
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
Reputation: 3964
For learners who rely on the IDE to fix this issue, you need to enable the image view's user interaction.
Upvotes: 1
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
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