[Swift 5] Processing to close the keyboard on UITableView

Introduction

When I placed TextField or TextView in the cell of TableView, I had a little trouble in closing the keyboard when tapping other parts, so I will post it as a memorandum.

Operating environment

【Xcode】Version 12.0.1 【Swift】Version 5.3

Implementation code

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        //Generate an instance for tap recognition
        let tapGesture = UITapGestureRecognizer(
            target: self,
            action: #selector(dismissKeyboard))
        tapGesture.cancelsTouchesInView = false
        //Add to View
        view.addGestureRecognizer(tapGesture)
    }
    //Keyboard and closing process
    @objc public func dismissKeyboard() {
        view.endEditing(true)
    }

}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
        return cell
    }
    
}

class TableViewCell: UITableViewCell {
    
    @IBOutlet weak var textField: UITextField!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        textField.delegate = self
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

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

Implementation details

First, I tried to get the touch event with the following function prepared in Swift and close the keyboard, but the process was not called. It seems that ʻUIScrollView and ʻUITableView cannot get touch events by default.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

The above method didn't work, so the solution is to use ʻUITapGestureRecognizer` to recognize the tap. Changed to close the keyboard.

//Generate an instance for tap recognition
let tapGesture = UITapGestureRecognizer(
    target: self,
    action: #selector(dismissKeyboard))
view.addGestureRecognizer(tapGesture)
//Keyboard and closing process
@objc public func dismissKeyboard() {
    view.endEditing(true)
}

ʻIf UITapGestureRecognizeris set, Tap to other views will not be recognized. The reason seems to be thatcancelsTouchesInView is true` by default, and it can be solved by adding the following code.

tapGesture.cancelsTouchesInView = false

In my opinion, I faced this issue when implementing the registration screen of the original app, except for TextView and TextField, which are in focus while the keyboard is displayed. I think it's okay not to touch it.

reference

Recommended Posts

[Swift 5] Processing to close the keyboard on UITableView
[Swift] How to dynamically change the height of the toolbar on the keyboard
[Swift] Processing to share screenshots
[Swift 5] Processing and precautions for transitioning to the iOS settings app
I want to remove the top margin in Grouped UITableView (swift)
Shorten the UUID to base64 in Swift.
[Processing × Java] How to use the loop
[Swift] How to implement the countdown function
How to change the timezone on Ubuntu
[Processing × Java] How to use the class
[Processing × Java] How to use the function
How to debug the processing in the Ruby on Rails model only on the console
Pre-processing to display on the browser (compiler)
Migration from Eclipse to IntelliJ (on the way)
[Swift] How to implement the LINE login function
[swift5] How to implement the Twitter share function
How to add sound in the app (swift)
Ssh login to the app server on heroku
[Swift] How to link the app with Firebase
Double-click to open the jar file on Windows
[Swift] How to implement the fade-in / out function
[Note] About the introduction to Swift practice Chapter 11
About keyboard events on Mac Catalyst [Xcode & Swift]
[Java] Memo on how to write the source
Starting with iOS 14, text fields are automatically adjusted to be hidden on the keyboard.
[Ruby on Rails] How to change the column name
[Swift] Use UserDefaults to save data in the app
[swift5] How to execute processing when tabBar is tapped
Deploy the Spring Boot project to Tomcat on XAMPP
Install MySQL 5.6 on CentOS6 [How to specify the version]
[Swift] How to get the document ID of Firebase
I want to return the scroll position of UITableView!
I want to simplify the log output on Android