Skip to content

Instantly share code, notes, and snippets.

@prafullakumar
Created August 3, 2020 07:35
Show Gist options
  • Save prafullakumar/dc60635e8ddbcc3848997fbc61aed1b6 to your computer and use it in GitHub Desktop.
Save prafullakumar/dc60635e8ddbcc3848997fbc61aed1b6 to your computer and use it in GitHub Desktop.
//https://stackoverflow.com/questions/56491881/move-textfield-up-when-the-keyboard-has-appeared-in-swiftui
import SwiftUI
final class KeyboardResponder: ObservableObject {
private var notificationCenter: NotificationCenter
@Published private(set) var currentHeight: CGFloat = 0
init(center: NotificationCenter = .default) {
notificationCenter = center
notificationCenter.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
deinit {
notificationCenter.removeObserver(self)
}
@objc func keyBoardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
currentHeight = keyboardSize.height
}
}
@objc func keyBoardWillHide(notification: Notification) {
currentHeight = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment