Search code examples
iosswiftuitextfielduitextviewdelegate

What is difference between the return value of the method named "textFieldShouldReturn(textField:)"?


I have doubts when i implement the delegate method textFieldShouldReturn of UITextField, I don't know what's difference between the return value.

I have tried return false and return true in it, but I didn't find the difference between them, and my custom delegate methods are all executed, the program seems to work fine. 😅

Here is my code:

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let legalInput = tagTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        if !legalInput.isEmpty {
            if isUpdate {
                if tag!.tagName != legalInput {
                    delegate?.didUpdateTagName(tagName: legalInput)
                }
            } else {
                delegate?.didAddTag(tagName: legalInput, themeId: themeId)
            }
        }
        navigationController?.popViewController(animated: true)

        // return false
        return true
    }

Solution

  • YES if the text field should implement its default behavior for the return button; otherwise, NO.

    The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped. For example, if you want to dismiss the keyboard when the user taps the return button, your implementation can call the resignFirstResponder method.

    You can read it on docs.

    If you want to hide the keyboard when the user clicks return button then

    return true
    

    otherwise default is false , the logic depends on your UX of whether you want the keyboard visible all time or not.