Created
May 31, 2020 00:41
-
-
Save JadenGeller/f8b89a5ef0f39f66a1016acf251c9a92 to your computer and use it in GitHub Desktop.
keyboardPadding SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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