Before you break your actual keyboard, let me show you the way.

SwiftUI, Apple’s declarative framework for rapid user interface development, has continued to mature as a useful alternative to UIKit with a 2.0 release at WWDC this year. As a newbie to the framework, I enjoy the instant feedback that the canvas preview provides with each code modification and am thoroughly impressed by the elegance and simplicity of SwiftUI’s design. That being said, I have run into odd behaviors and challenging problems that make me want to tear my hair out at times. One such issue, which at first seems trivial, is how to dismiss the keyboard when a user taps an area on the screen that is outside the bounds of a TextField or TextEditor view. Here, I will discuss a few of the common issues surrounding keyboard dismissal and provide two solutions and workarounds that I have found after an embarrassing amount of googling and reading on StackOverflow.

Notes: 1. A demo iOS app that accompanies this post is available on GitHub. This article was written using XCode 12.1, SwiftUI 2.0, and compiled for iOS 14.1.

The crux of the problem

If you have already spent an hour trying to figure out how to dismiss the keyboard in SwiftUI you are not alone. SwiftUI doesn’t currently expose a mechanism for manual keyboard dismissal from within its own framework, so we have to fall back on UIKit. In UIKit, views that utilize the keyboard such as UITextField and UITextView can be dismissed by calling resignFirstResponder on the view itself, or endEditing on one of its parent views. Code in a simple view controller might look like this:

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        self.view.addGestureRecognizer(tapGesture)
    }

    @IBAction func buttonPressed(_ sender: Any) {
        dismissKeyboardFrom(view: textField)
    }

    @objc func dismissKeyboardFrom(view: UIView) {
        view.resignFirstResponder()
        // or view.endEditing()
    }

    @objc func dismissKeyboard() {
        self.view.endEditing(true)
    }
}

#ios #swiftui #programming #developer #swift

Dismissing the Keyboard in SwiftUI 2.0
6.05 GEEK