Reputation: 1791
This should be simple, but it's becoming a headache. I have a view with a UITextField where the user types some text and clicks search. This pops up another view controller, and I resign first responder on the text field before the first view disappears. When the second view gets dismissed, the first view automatically makes the text field become first responder again and I can't find a way to suppress this. Does anyone have any idea how I can keep the keyboard from popping up when I dismiss the second view?
I tried to resignFirstResponder in viewWillAppear, no effect. I tried the same in viewDidAppear, but the keyboard pops up and then immediately dismisses which is awkward looking.
I appreciate any help.
Upvotes: 13
Views: 3563
Reputation: 581
Please add those Line in your code in my case "tfCode1"
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
_ = self.tfCode1.becomeFirstResponder()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
_ = self.tfCode1.resignFirstResponder()
}
Upvotes: 0
Reputation: 1389
I had a similar issue - a UITextView in View Controller A was the first responder. When tapping another UI element on the screen I pushed View Controller B onto the nav stack, but when the back button was pushed and View Controller A was shown again, the UITextView was still first responder.
I solved the issue by calling resignFirstResponder
on the text view in View Controller A's viewWillDisappear
. Note that this does not work if you call it in viewDidDisappear
, since at that point the text view is no longer first responder. It's important to make sure that the text view is actually the first responder when you call resignFirstResponder
, otherwise resigning has no effect. You can check this for debugging purposes by inspecting isFirstResponder
on the text view.
Upvotes: 0
Reputation: 4705
I found a fix, but its not a very good one.
Found that canBecomeResponder message was being passed to the textfield right after viewWillAppear
and before viewDidAppear
.
So I set a BOOL value in viewDidAppear
to YES, and used that value in textField:shouldBeginEditing
method. Basically if the viewDidAppear
was not called yet, textField:shouldBeginEditing
was returning NO.
Upvotes: 9