View+KeyboardAware.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //
  2. // View+KeyboardAware.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 7/22/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import SwiftUI
  9. // NOTE: In iOS 14, keyboard management is handled automatically in SwiftUI.
  10. extension View {
  11. public func onKeyboardStateChange(perform updateForKeyboardState: @escaping (_ keyboardHeight: Keyboard.State) -> Void) -> some View {
  12. onReceive(Keyboard.shared.$state, perform: updateForKeyboardState)
  13. }
  14. public func keyboardAware() -> some View {
  15. modifier(KeyboardAware())
  16. }
  17. }
  18. fileprivate struct KeyboardAware: ViewModifier {
  19. @State var keyboardHeight: CGFloat = 0
  20. func body(content: Content) -> some View {
  21. content
  22. .padding(.bottom, keyboardHeight)
  23. .edgesIgnoringSafeArea(keyboardHeight > 0 ? .bottom : [])
  24. .onKeyboardStateChange { state in
  25. if state.height == 0 {
  26. // Only animate the transition as the keyboard comes up; animating the opposite direction is jittery.
  27. self.keyboardHeight = 0
  28. } else {
  29. withAnimation(.easeInOut(duration: state.animationDuration)) {
  30. self.keyboardHeight = state.height
  31. }
  32. }
  33. }
  34. }
  35. }