resign first responder UITextfield

Peter Boesen picture Peter Boesen · May 26, 2016 · Viewed 9.3k times · Source

I am so sorry to post this, since it has been asked a million of times, but whenever i try to use one of the solutions, it is either outdated, or won't work with my code. (or maybe i am just doing it wrong)

i have 5 textfields and a textview, that go into an email, and i am trying to minimise the keyboard when im done, but i dont know how to. I also tried to make it go to the next text field, until the last one, but that doesn't need to be done.

Im very new btw. so plz be very specific :D

code:

    func textView(textView: UITextView, shouldChangeTextInRange: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        text6.resignFirstResponder()
        return false
    }
    return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {

    if textField == self.text1 {
        self.text2.becomeFirstResponder()
    }
    else if textField == self.text2 {
        self.text3.becomeFirstResponder()
    }
    else if textField == self.text3 {
        self.text4.becomeFirstResponder()
    }

    else if textField == self.text4 {
        self.text5.becomeFirstResponder()
        self.text5.resignFirstResponder();
    }

    return true;
}

Answer

user5938635 picture user5938635 · May 26, 2016

first you have to add UITextFieldDelegate in .h

then in .m

yourtextfield.delegate = self

then apply this code

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