Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. //
  2. // Notification+Extension.swift
  3. //
  4. //
  5. // Created by Amit Kumar Swami on 20/08/17.
  6. // Copyright © 2017 aks.swami. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11.  
  12. class Token {
  13. let center: NotificationCenter
  14. let token: NSObjectProtocol
  15.  
  16. init(token: NSObjectProtocol, center: NotificationCenter) {
  17. self.token = token
  18. self.center = center
  19. }
  20.  
  21. deinit {
  22. center.removeObserver(token)
  23. }
  24. }
  25.  
  26. struct NotificationDescriptor<A> {
  27. let name: Notification.Name
  28. let convert: (Notification) -> A
  29. }
  30.  
  31. extension NotificationCenter {
  32. func addObserver<A>(forDescriptor d: NotificationDescriptor<A>, using block: @escaping (A) -> ()) -> Token {
  33. let t = addObserver(forName: d.name, object: nil, queue: nil, using: { note in
  34. block(d.convert(note))
  35. })
  36. return Token(token: t, center: self)
  37. }
  38. }
  39.  
  40. struct KeyboardPayload {
  41. let size: CGSize
  42. }
  43.  
  44. extension KeyboardPayload {
  45. init(note: Notification) {
  46. guard let userInfo = note.userInfo,
  47. let value = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue
  48. else {
  49. size = CGSize.zero
  50.  
  51. return
  52. }
  53. size = value.cgRectValue.size
  54. }
  55. }
  56.  
  57. let keyboardShowNotification = NotificationDescriptor<KeyboardPayload>(name: Notification.Name.UIKeyboardWillShow, convert: KeyboardPayload.init)
  58. let keyboardHiderNotification = NotificationDescriptor<KeyboardPayload>(name: Notification.Name.UIKeyboardWillHide, convert: KeyboardPayload.init)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement