Keyboard.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // Keyboard.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 7/18/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import Combine
  9. import UIKit
  10. public final class Keyboard: ObservableObject {
  11. public struct State {
  12. public var height: CGFloat = 0
  13. public var animationDuration: TimeInterval = 0.25
  14. }
  15. @Published var state = State()
  16. private var keyboardFrameChangeCancellable: AnyCancellable?
  17. static let shared = Keyboard()
  18. private init() {
  19. keyboardFrameChangeCancellable = NotificationCenter.default
  20. .publisher(for: UIResponder.keyboardWillChangeFrameNotification)
  21. .receive(on: DispatchQueue.main)
  22. .sink { [weak self] notification in
  23. guard let self = self, let userInfo = notification.userInfo else {
  24. return
  25. }
  26. let height: CGFloat
  27. if let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
  28. height = UIScreen.main.bounds.intersection(keyboardFrame).height
  29. } else {
  30. height = 0
  31. }
  32. let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0.25
  33. self.state = State(height: height, animationDuration: animationDuration)
  34. }
  35. }
  36. }