Set UITextField Keyboard Return Key as Done button And Dismiss Keyboard

In this short Swift code example we will learn how to create UITextField in Swift programmatically as well as how to set Keyboard return button as Done button and how to handle Done button to dismiss keyboard.

  • Create UITextField of specific height and width
  • Position UITextField at the centre of the view
  • Set UITextField backgroundColor
  • Set UITextField returnKeyType as Done button
  • Handle Keyboard Done button to dismiss keyboard

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

import UIKit

class ViewController: UIViewController, UITextFieldDelegate  {

override func viewDidLoad() {

override func viewWillAppear(_ animated: Bool) {
    let textField = UITextField(frame: CGRect(x: 20.0, y:90.0, width: 280.0, height: 44.0))
    textField.delegate = self
    textField.returnKeyType = .done
    textField.backgroundColor = UIColor.lightGray

func textFieldShouldReturn(_ textField: UITextField) -> Bool
    return true

Watch this video tutorial to learn how to dismiss UITextField keyboard

Dismiss keyboard example in Swift

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.