Guest User

Untitled

a guest
Feb 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. //
  2. // KeyboardAlignmentHandler.swift
  3. // MandelPlay-iOS
  4. //
  5. // Created by Patrik Sjöberg on 2017-10-18.
  6. // Copyright © 2017 Com Hem AB. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. /**
  12. A class that can be dropped in to InterfaceBuilder to handle keyboard animations
  13.  
  14. Drop a view (keyboard animation wrapper) into your viewcontrollers view and constraint it to it's superviews edges.
  15. Drop an Object reference and set it's class to KeyboardAlignmentHandler
  16. Bind the keyboard animation wrapper view to KeyboardAlignmentHandler's view
  17. Bind the keyboard animation wrapper views bottom constraint to the KeyboardAlignmentHandler's constraints collection
  18. */
  19. class KeyboardAlignmentHandler: NSObject {
  20. /// The view that will be pushed up by the keyboard
  21. @IBOutlet weak var view: UIView? = nil
  22. /// The bottom constraint for the view
  23. @IBOutlet var constraints: [NSLayoutConstraint] = []
  24.  
  25.  
  26.  
  27. var notificationObservers: [NSObjectProtocol] = []
  28.  
  29. var notificationCenter: NotificationCenter {
  30. return NotificationCenter.default
  31. }
  32.  
  33. override init() {
  34. super.init()
  35.  
  36. notificationObservers = [
  37. notificationCenter.addObserver(forName: .UIKeyboardWillChangeFrame, object: nil, queue: nil, using: keyboardFrameDidChange)
  38. ]
  39. }
  40.  
  41. convenience init(view: UIView, constraints: [NSLayoutConstraint]) {
  42. self.init()
  43. self.constraints = constraints
  44. self.view = view
  45. }
  46.  
  47. func keyboardFrameDidChange(_ notification: Notification) {
  48. guard
  49. let view = view,
  50. let superview = view.superview,
  51. let userInfo = notification.userInfo,
  52. let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect
  53. else { return }
  54.  
  55. let targetRect = view.convert(keyboardFrame, from: nil)
  56. let calculatedHeight = targetRect.intersection(superview.bounds).height
  57. for constraint in constraints {
  58. if constraint.firstItem === view {
  59. constraint.constant = -calculatedHeight
  60. }
  61. if constraint.secondItem === view {
  62. constraint.constant = calculatedHeight
  63. }
  64. }
  65.  
  66. let animated = view.window != nil
  67.  
  68. if animated, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval {
  69. view.setNeedsLayout()
  70. UIView.animate(withDuration: duration, animations: {
  71. view.superview?.layoutIfNeeded()
  72. })
  73. }
  74. }
  75. }
Add Comment
Please, Sign In to add comment