Reputation: 583
I am hiding keyboard on return key pressed by implementing function textFieldShouldReturn
and calling resignFirstResponder()
inside this function. It works perfectly but when I return false
in this function, still then keyboard is hiding. Now here I do not understand that what is use of returning true
or false
if keyboard is hiding in both case?
Upvotes: 8
Views: 1664
Reputation: 346
It's been a long time since I worked on Native iOS. Nearly 2 years. I've just picked up swift 5 and working through the forgotten and new parts right from the basics. Here's what i have observed.
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if searchTextField.text != "" {
return true
}
searchTextField.placeholder = "Type Something"
return false
}
Here when I press the return key without typing a single letter in it, Keyboard does not dismiss. Rather the placeholder text changes to notify user to type something. The magic of returning false
from textFieldShouldEndEditing
.
If I press the same return key after entering at the very least a single character, it simply dismisses the keyboard. Courtesy of returning a true
from the same textFieldShouldEndEditing
.
I also didn't observe any difference when I placed textField.resignFirstResponder()
regardless if I return true
or false
.
Conclusion:
true
dismisses the keyboard. false
stops the keyboard from dismissiong.
Upvotes: 0
Reputation: 33
I have tried that wether true or false, the keyboard do dismiss, here is the code:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
The keyboard do dismiss or not depends on "textField.resignFirstResponder()", if you delete it, the keyboard does no longer dismiss, whether true or false.
Upvotes: 0
Reputation: 534893
The return value from textFieldShouldReturn
answers a different question. If the text field has an action for the control event editingDidEndOnExit
, that will cause the keyboard to dismiss unless textFieldShouldReturn
is implemented to return false
.
Upvotes: 4
Reputation: 318774
The keyboard is being dismissed due to the call to resignFirstResponder
. It has nothing at all to do with the return value of textFieldShouldReturn
.
In my experience, the return value of textFieldShouldReturn
almost has no use. In the vast majority of cases it makes no difference whether you return true
, or false
.
I return false
in all my uses of testFieldShouldReturn
. If you return true
and your implementation of textFieldShouldReturn
sets the first responder to a UITextView
, the text view ends up getting the newline added to it. Returning false
from textFieldShouldReturn
ensures this won't happen. But this was based on experience with iOS 4 or 5 a few years ago. I don't know if that still happens with the latest versions of iOS.
Upvotes: 10