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.
【Xcode】Version 12.0.1 【Swift】Version 5.3
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
}
}
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 that
cancelsTouchesInView 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.
Recommended Posts