Skip to content

Instantly share code, notes, and snippets.

@colejd
Created October 27, 2022 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colejd/04259a7087d3a7a6578e3da25ecdb1a5 to your computer and use it in GitHub Desktop.
Save colejd/04259a7087d3a7a6578e3da25ecdb1a5 to your computer and use it in GitHub Desktop.
/**
Adapted from here:
https://www.vadimbulavin.com/how-to-move-swiftui-view-when-keyboard-covers-text-field/
Use these publishers to know when the keyboard is about to hide or show.
As an example, you can use this to scroll a ScrollView automatically after
the keyboard shows, using the timing information provided here.
*/
import Combine
import SwiftUI
extension Publishers {
static var keyboardWillChange: AnyPublisher<(height: CGFloat, animationDuration: TimeInterval), Never> {
let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification)
.map {
(height: $0.keyboardHeight, animationDuration: $0.keyboardAnimationDuration)
}
let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification)
.map {
(height: CGFloat(0), animationDuration: $0.keyboardAnimationDuration)
}
return MergeMany(willShow, willHide)
.eraseToAnyPublisher()
}
}
extension Notification {
var keyboardHeight: CGFloat {
return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0
}
var keyboardAnimationDuration: TimeInterval {
return (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment