Search code examples
iosswiftuitextfielduitextfielddelegate

Clicking "Done" on keyboard to dismiss keyboard, but it will not be dismissed


I am trying to dismiss the keyboard by clicking the "Done" button but it will not be dismissed. Here is what I have done so far:

I have also added protocol UITextFieldDelegate.

override func viewDidLoad() {
    super.viewDidLoad()

    texts.layer.cornerRadius = 10
    texts.delegate = self
    texts.keyboardType = .numbersAndPunctuation
    texts.returnKeyType = .done
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {   //delegate method
    var number = CGFloat((texts.text! as NSString).floatValue)

    slide.setValue(Float(number), animated: true)

    textField.resignFirstResponder()

    return true
}

I want it to dismiss so that entered value can be stored in the number variable and the app can move on.


Solution

  • Most likely your textFieldShowReturn isn't being called since it has the wrong signature. Some quick use of the debugger (or a print statement) will confirm.

    It should be:

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // your code here
    }
    

    Note the _ for the parameter label.