Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Notification+Extension.swift
- //
- //
- // Created by Amit Kumar Swami on 20/08/17.
- // Copyright © 2017 aks.swami. All rights reserved.
- //
- import Foundation
- import UIKit
- class Token {
- let center: NotificationCenter
- let token: NSObjectProtocol
- init(token: NSObjectProtocol, center: NotificationCenter) {
- self.token = token
- self.center = center
- }
- deinit {
- center.removeObserver(token)
- }
- }
- struct NotificationDescriptor<A> {
- let name: Notification.Name
- let convert: (Notification) -> A
- }
- extension NotificationCenter {
- func addObserver<A>(forDescriptor d: NotificationDescriptor<A>, using block: @escaping (A) -> ()) -> Token {
- let t = addObserver(forName: d.name, object: nil, queue: nil, using: { note in
- block(d.convert(note))
- })
- return Token(token: t, center: self)
- }
- }
- struct KeyboardPayload {
- let size: CGSize
- }
- extension KeyboardPayload {
- init(note: Notification) {
- guard let userInfo = note.userInfo,
- let value = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue
- else {
- size = CGSize.zero
- return
- }
- size = value.cgRectValue.size
- }
- }
- let keyboardShowNotification = NotificationDescriptor<KeyboardPayload>(name: Notification.Name.UIKeyboardWillShow, convert: KeyboardPayload.init)
- let keyboardHiderNotification = NotificationDescriptor<KeyboardPayload>(name: Notification.Name.UIKeyboardWillHide, convert: KeyboardPayload.init)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement