Skip to content

Hide keyboard with buttons in SwiftUI

   

It is a way to hide the keyboard with a button in SwiftUI. It is realized by extending UIApplication.

HideKeyboard

How to lower (hide) the keyboard in SwiftUI

import SwiftUI
struct ContentView: View {
@State var text: String = ""
@ObservedObject var keyboard: KeyboardObserver = KeyboardObserver()
var body: some View {
VStack {
TextField("Input Your Text", text: $text)
.padding()
Text("KeyboardHeight: \(keyboard.height)")
Text("\(keyboard.isShowing ? "Keyboard Is Showing" : "Keyboard Is Not Showing")")
Spacer()
}.onAppear{
self.keyboard.addObserver()
}.onDisappear {
self.keyboard.removeObserver()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
class KeyboardObserver: ObservableObject {
@Published var isShowing = false
@Published var height: CGFloat = 0
func addObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func removeObserver() {
NotificationCenter.default.removeObserver(self,name: UIResponder.keyboardWillShowNotification,object: nil)
NotificationCenter.default.removeObserver(self,name: UIResponder.keyboardWillHideNotification,object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
isShowing = true
guard let userInfo = notification.userInfo as? [String: Any] else {
return
}
guard let keyboardInfo = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardSize = keyboardInfo.cgRectValue.size
height = keyboardSize.height
}
@objc func keyboardWillHide(_ notification: Notification) {
isShowing = false
height = 0
}
}

  1. Create a sequential numbered array in Swift
  2. Detect keyboard height and appearance with SwiftUI
  3. Input a multi-line string with SwiftUI
  4. Show picker from bottom with SwiftUI
  5. Using UIImagePickerController with SwiftUI
  6. Do not change the color of the Image in the Button with SwiftUI
  7. I tried all the ModalPresentationStyle of iOS 13