Skip to content

Instantly share code, notes, and snippets.

@robertofrontado
Created May 17, 2016 17:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertofrontado/6537d6757d5243b4677bbb4792879d0b to your computer and use it in GitHub Desktop.
Save robertofrontado/6537d6757d5243b4677bbb4792879d0b to your computer and use it in GitHub Desktop.
Useful Rx tool to works with the Keyboard states in iOS
//
// RxKeyboard.swift
// RxTools
//
// Created by Roberto Frontado on 5/16/16.
// Copyright © 2016 Roberto Frontado. All rights reserved.
//
import RxSwift
public class RxKeyboard: NSObject {
private var subscribe: AnyObserver<(state: State, duration: Double, keyboardRectangle: CGRect)>!
public enum State {
case WillShow
case DidHide
case DidChange
}
public override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidChange:", name: UIKeyboardDidChangeFrameNotification, object: nil)
}
public func getCurrentState() -> Observable<(state: State, duration: Double, keyboardRectangle: CGRect)> {
return Observable.create { subscribe -> Disposable in
self.subscribe = subscribe
return NopDisposable.instance
}
}
public func dispose() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Keyboard
public func keyboardWillShow(notification: NSNotification) {
subscribe.onNext((state: .WillShow, duration: getDuration(notification), keyboardRectangle: getKeyboardRectangle(notification)))
}
public func keyboardDidChange(notification: NSNotification) {
subscribe.onNext((state: .DidChange, duration: getDuration(notification), keyboardRectangle: getKeyboardRectangle(notification)))
}
public func keyboardDidHide(notification: NSNotification) {
subscribe.onNext((state: .DidHide, duration: getDuration(notification), keyboardRectangle: getKeyboardRectangle(notification)))
}
// MARK: - Private methods
private func getKeyboardRectangle(notification: NSNotification) -> CGRect {
let userInfo: NSDictionary = notification.userInfo!
let keyboardFrame = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
return keyboardFrame.CGRectValue()
}
private func getDuration(notification: NSNotification) -> Double {
let userInfo: NSDictionary = notification.userInfo!
return (userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey) as? NSNumber)?.doubleValue ?? 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment