R. Harrison
R. Harrison

Reputation: 13

Make UITextField clear content each time return key pressed

I'm learning Swift by making a times tables app, which simply creates random times tables and asks the user to type the answer in a UITextField.

I'd like the user to be able to tap the return key and have the text field clear their previous answer and have the keyboard remain in view. I've already set up the other behaviour I want, it's just I can't seem to find any similar questions to figure out how to clear, and do all this when there return key is tapped.

Here's the code I have so far, which works when dismissing the keyboard, and doesn't clear the field.

Many thanks!

@IBAction func answerTyped(_ sender: UITextField) {

    /* Clear the text field*/

    questionNumber += 1
    attempted += 1
    markQuestion(answer: answer)
    newQuestion(awardLevel: currentLevel, questionNumber: questionNumber)
}

Upvotes: 1

Views: 457

Answers (2)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

If you want the textField to be cleared on tapping return button you can use the textFieldShouldReturn delegate.

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
   textField.text = "" // Clears text
   //Do other things that you want to do when user taps return button
   return true
}

Note that this wont dismiss the textField like how you asked and usually users are used to dismissing their textField using return. So if you ask me this is not good UX. And you need to have a mechanism for the user to dismiss the keyboard if needed like tap outside to dismiss or something. So i hope you have that sorted out.

Your viewController should have implemented the UITextFieldDelegate for this method work.

class YourViewController: UITextFieldDelegate {
    var textField: UITextField! //Using IBOutlet or whatever

    func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self
    }
}

Upvotes: 0

Augie
Augie

Reputation: 1341

you will need to make something, likely your view controller containing this text field into a uitextfieldelegate, then add the necessary delegate functions.

I think the function you want is TextField:DidEndEditing:Reason https://developer.apple.com/documentation/uikit/uitextfielddelegate/2352220-textfielddidendediting

Or you can just use

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

which is called every time user hits the return key. You would need to add your logic to clear the contents before the returns.

Upvotes: 0

Related Questions