Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created May 31, 2020 00:41
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 JadenGeller/f8b89a5ef0f39f66a1016acf251c9a92 to your computer and use it in GitHub Desktop.
Save JadenGeller/f8b89a5ef0f39f66a1016acf251c9a92 to your computer and use it in GitHub Desktop.
keyboardPadding SwiftUI
import SwiftUI
import Combine
struct KeyboardPaddingModifier: ViewModifier {
@State private var keyboardMinY: CGFloat? = nil
private var keyboardNotificationPublisher: AnyPublisher<Notification, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification),
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
).eraseToAnyPublisher()
}
func overlappingHeight(in geometry: GeometryProxy) -> CGFloat {
guard let keyboardMinY = keyboardMinY else {
return 0
}
return max(0, geometry.frame(in: .global).maxY - keyboardMinY)
}
func body(content: Content) -> some View {
GeometryReader { geometry in
content
.padding(.bottom, self.overlappingHeight(in: geometry))
}.onReceive(keyboardNotificationPublisher) { notification in
let keyboardFrameEnd = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey]! as! CGRect
let keyboardAnimationDuration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
withAnimation(.easeOut(duration: keyboardAnimationDuration)) {
self.keyboardMinY = keyboardFrameEnd.minY
}
}
}
}
extension View {
func keyboardPadding() -> some View {
modifier(KeyboardPaddingModifier())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment