Best way to dismiss Keyboard in a View Controller iOS (Swift)

Overview

Best way to dismiss Keyboard in a View Controller iOS (Swift)

First way: Implement UITextFieldDelegate’s textFieldShouldReturn method and dismiss current keyboard.

This solution seems good enough but not all keyboards have return button.

iPhone_12

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var text1: UITextField!
    @IBOutlet weak var text2: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        text1.delegate = self
        text2.delegate = self

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

Second way: when textfield has no return keys eg. (UIKeyboardType.numberPad)

iPhone_12

class ViewController: UIViewController {
    
    @IBOutlet weak var text1: UITextField!
    @IBOutlet weak var text2: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupTextFields()
        
    }
    
    func setupTextFields() {
        let toolbar = UIToolbar()
        let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                                        target: nil, action: nil)
        let doneButton = UIBarButtonItem(title: "Done", style: .done,
                                         target: self, action: #selector(doneButtonTapped))
        
        toolbar.setItems([flexSpace, doneButton], animated: true)
        toolbar.sizeToFit()
        
        text1.inputAccessoryView = toolbar
        text2.inputAccessoryView = toolbar
    }
    
    @objc func doneButtonTapped() {
        view.endEditing(true)
    }
}

iPhone_12

Third: what could be better than tapping anywhere on the view controller to dismiss the keyboard.

Just one line of code would serve our purpose. Add a tap gesture recogniser on self.view, set target as self.view and set selector as endEditing: (in ViewDidLoad() or anywhere you like)

class ViewController: UIViewController {
    
    @IBOutlet weak var text1: UITextField!
    @IBOutlet weak var text2: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tap = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
        
    }

iPhone_12

You might also like...
A Chinese keyboard for iOS that helps Chinese language learners remember tones.
A Chinese keyboard for iOS that helps Chinese language learners remember tones.

ToneBoard ToneBoard is a Chinese keyboard for iOS that requires you to enter the correct tones while typing simplified Chinese with Pinyin. It is avai

SwiftyKeyboard: a full customized numeric keyboard for iOS
SwiftyKeyboard: a full customized numeric keyboard for iOS

SwiftyKeyboard Overview SwiftyKeyboard is an iOS customized enhanced keyboard. T

Emoji Keyboard for iOS
Emoji Keyboard for iOS

English | 中文 An easy to use Emoji keyboard for iOS. Has been rewritten with swift, the old Objective-C version on branch oc. Features Written in Swift

Prevent keyboard from covering UITextField/UITextView, includes Swift and Objective-C APIs

Prevent keyboard from covering UITextField/UITextView with only one line of code, includes Swift and Objective-C APIs.

IHKeyboardAvoiding is an elegant solution for keeping any UIView visible when the keyboard is being shown - no UIScrollView required!
IHKeyboardAvoiding is an elegant solution for keeping any UIView visible when the keyboard is being shown - no UIScrollView required!

IHKeyboardAvoiding An elegant solution for keeping any UIView visible when the keyboard is being shown Requirements IHKeyboardAvoiding Version Objecti

Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.

IQKeyboardManager While developing iOS apps, we often run into issues where the iPhone keyboard slides up and covers the UITextField/UITextView. IQKey

⌨️ Add user-customizable global keyboard shortcuts to your macOS app in minutes
⌨️ Add user-customizable global keyboard shortcuts to your macOS app in minutes

This package lets you add support for user-customizable global keyboard shortcuts to your macOS app in minutes. It's fully sandbox and Mac App Store c

Suppress mouse & keyboard events on MacOSX. Baby-proof my Mac!

Suppress mouse & keyboard events on MacOSX Catches all events (mouse, keyboard, everything), and either consumes them (locked state) or passes them th

QMK Agent is a macOS menubar application which sends commands to a QMK enabled keyboard
QMK Agent is a macOS menubar application which sends commands to a QMK enabled keyboard

QMKagent QMK Agent is a macOS menubar application which sends commands to a QMK enabled keyboard Features System volume indicator using top row (Esc t

Owner
iOS Developer.Currently passionate about Mobile. Background with Java.
null
Interactive Keyboard Controller for Swift

Keynode Why Using UIScrollViewKeyboardDismissMode added in iOS7, interactive keyboard operation became possible. But, it only works on UIScrollView. K

Kyohei Ito 76 Sep 1, 2020
A drop-in universal solution for moving text fields out of the way of the keyboard in iOS

TPKeyboardAvoiding A drop-in universal solution for moving text fields out of the way of the keyboard in iOS. Introduction There are a hundred and one

Michael Tyson 5.8k Dec 26, 2022
⌨️A Combine-based way to observe and adjust for Keyboard notifications in SwiftUI

⌨️ Keyboard Observing A Combine-based solution for observing and avoiding the keyboard in SwiftUI. Table of Contents About Requirements Installation C

Nick Fox 440 Jan 5, 2023
HomeWork3.2 - How to work with sliders, textfield, keyboard, view

HomeWork3.2 How to work with sliders, textfield, keyboard, view

Artur 1 Jan 26, 2022
Codeless manager to hide keyboard by tapping on views for iOS written in Swift

KeyboardHideManager KeyboardHideManager - codeless manager to hide keyboard by tapping on views for iOS written in Swift. Structure Features Requireme

Bondar Yaroslav 55 Oct 19, 2022
Swift UIKit keyboard manager for iOS apps.

Typist Typist is a small, drop-in Swift UIKit keyboard manager for iOS apps. It helps you manage keyboard's screen presence and behavior without notif

Toto Tvalavadze 1.1k Dec 10, 2022
KeyboardKit is a Swift library that helps you create custom keyboard extensions for iOS and ipadOS.

KeyboardKit is a Swift library that helps you create custom keyboard extensions for iOS and ipadOS.

KeyboardKit 900 Jan 9, 2023
Slidden is an open source, customizable, iOS 8 keyboard, written in Swift

Slidden is an open source, customizable, iOS 8 keyboard, written in Swift. iOS 8 brought us the ability to create fully customizable keyboards, but do

Daniel Brim 595 Jan 5, 2023
Objective-C library for tracking keyboard in iOS apps.

NgKeyboardTracker Objective-c library for tracking keyboard in iOS apps. Adding to your project If you are using CocoaPods, add to your Podfile: pod '

Meiwin Fu 808 Nov 17, 2022
Emoji Keyboard SDK (iOS)

Makemoji SDK Makemoji is a free emoji keyboard for mobile apps. By installing our keyboard SDK every user of your app will instantly have access to ne

Makemoji 100 Nov 3, 2022