Swift 5: How to programmatically dismiss a keyboard when return is clicked

For the sake of this article, I will be doing everything programmatically.

  1. Make a new textField in your ViewController.swift file and add constraints

2. Set the textField’s delegate to self. Place paste this code on the line below the textField’s constraints (under line 21).

3. Extend the ViewController class with the following code. The textFieldShouldReturn function will be called whenever the return button is clicked.

4. Now finally combine all of the code so that it looks like this

Congratulations! You now know how to programmatically make the keyboard disappear when the return button is clicked!

I make tutorials and articles on Programming, iOS Development, and Mathematics github.com/EricGustin