abuosama
abuosama

Reputation: 29

Swift: UITextField keyboard return key is not working

Below is my code for hiding keyboard on pressing return key, But it's not working.

class AddHall: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var hallname: UITextField!

     override func viewDidLoad() {
         super.viewDidLoad()

         hallname.delegate = self
    }


    func textFieldShouldReturn(hallname : UITextField!) -> Bool { 
        hallname.resignFirstResponder()
        return true
    }
}

Upvotes: 1

Views: 4569

Answers (5)

Jacob Harrington
Jacob Harrington

Reputation: 11

None of these worked alone for me. Rather:

  1. Ensure ViewController extends from both:
class ViewController: UIViewController, UITextFieldDelegate 
  1. Add delegate from TextField to ViewController via Storyboard or programmatically:
textField.delegate = self
  1. Define function in ViewController:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
     self.view.endEditing(true)
     textField.resignFirstResponder()
     return false
}

Upvotes: -1

user4995679
user4995679

Reputation:

Implement correct UITextField Delegate method.

replace

func textFieldShouldReturn(hallname : UITextField!) -> Bool { 
    hallname.resignFirstResponder()
    return true
} 

with

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
     textField.resignFirstResponder()
     return true
}

Upvotes: 4

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

The delegate method textFieldShouldReturn is used to specify if the text field is allowed to lose the focus - it will only be called just before the UITextField is about to lose its focus. You should only do some checks her, but not dismiss anything.

What you seek is to react on the return key, and then dismiss the keyboard. This is done by connecting the DidEndOnExit action (be aware: there are a lot of other events with similar names, you'll have to exactly use this one), and there resign the first responder.

DidEndOnExit

You can then just remove textFieldShouldReturn (unless you do some additional checks here and not simply return true).

Upvotes: 1

Agent Smith
Agent Smith

Reputation: 2923

You have to use correct function name for TextField Delegate

Use this:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
     return true
}

Upvotes: 0

Sarath
Sarath

Reputation: 339

change your code like this. You are not using correct delegate method.

func textFieldShouldReturn(textField : UITextField!) -> Bool { 
    textField.resignFirstResponder()
    return true
}

Upvotes: 0

Related Questions