Skip to content

Detect keyboard height and appearance with SwiftUI

   

It is a way to detect keyboard height and appearance with SwiftUI. It is implemented using Combine Frame Work.

MultilineTextView

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. Input a multi-line string with SwiftUI
  3. Show picker from bottom with SwiftUI
  4. Using UIImagePickerController with SwiftUI
  5. Do not change the color of the Image in the Button with SwiftUI
  6. I tried all the ModalPresentationStyle of iOS 13
  7. Detect video end with Swift