KeyboardTranslation.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // KeyboardTranslation.swift
  3. // Presentr
  4. //
  5. // Created by Aaron Satterfield on 7/15/16.
  6. // Copyright © 2016 danielozano. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. public enum KeyboardTranslationType {
  11. case none
  12. case moveUp
  13. case compress
  14. case stickToTop
  15. /**
  16. Calculates the correct frame for the keyboard translation type.
  17. - parameter keyboardFrame: The UIKeyboardFrameEndUserInfoKey CGRect Value of the Keyboard
  18. - parameter presentedFrame: The frame of the presented controller that may need to be translated.
  19. - returns: CGRect representing the new frame of the presented view.
  20. */
  21. public func getTranslationFrame(keyboardFrame: CGRect, presentedFrame: CGRect) -> CGRect {
  22. let keyboardTop = UIScreen.main.bounds.height - keyboardFrame.size.height
  23. let presentedViewBottom = presentedFrame.origin.y + presentedFrame.height + 20.0 // add a 20 pt buffer
  24. let offset = presentedViewBottom - keyboardTop
  25. switch self {
  26. case .moveUp:
  27. if offset > 0.0 {
  28. let frame = CGRect(x: presentedFrame.origin.x, y: presentedFrame.origin.y-offset, width: presentedFrame.size.width, height: presentedFrame.size.height)
  29. return frame
  30. }
  31. return presentedFrame
  32. case .compress:
  33. if offset > 0.0 {
  34. let y = max(presentedFrame.origin.y-offset, 20.0)
  35. let newHeight = y != 20.0 ? presentedFrame.size.height : keyboardTop - 40.0
  36. let frame = CGRect(x: presentedFrame.origin.x, y: y, width: presentedFrame.size.width, height: newHeight)
  37. return frame
  38. }
  39. return presentedFrame
  40. case .stickToTop:
  41. if offset > 0.0 {
  42. let y = max(presentedFrame.origin.y-offset, 20.0)
  43. let frame = CGRect(x: presentedFrame.origin.x, y: y, width: presentedFrame.size.width, height: presentedFrame.size.height)
  44. return frame
  45. }
  46. return presentedFrame
  47. case .none:
  48. return presentedFrame
  49. }
  50. }
  51. }
  52. // MARK: Notification + UIKeyboardInfo
  53. extension Notification {
  54. /// Gets the optional CGRect value of the UIKeyboardFrameEndUserInfoKey from a UIKeyboard notification
  55. func keyboardEndFrame () -> CGRect? {
  56. return (self.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
  57. }
  58. /// Gets the optional AnimationDuration value of the UIKeyboardAnimationDurationUserInfoKey from a UIKeyboard notification
  59. func keyboardAnimationDuration () -> Double? {
  60. return (self.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
  61. }
  62. }