Skip to content

Instantly share code, notes, and snippets.

@jpiche
Created January 4, 2017 18:53
Show Gist options
  • Save jpiche/36cd80dad9aa1ca20d378e8542b99af9 to your computer and use it in GitHub Desktop.
Save jpiche/36cd80dad9aa1ca20d378e8542b99af9 to your computer and use it in GitHub Desktop.
import UIKit
public protocol KeyboardChangeDelegate {
func doKeyboardAnimateTo(toValue: CGFloat)
}
open class KeyboardChangeViewController: UIViewController {
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default
.addObserver(self,
selector: #selector(keyboardWillChange(_:)),
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil)
NotificationCenter.default
.addObserver(self,
selector: #selector(keyboardWillChange(_:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
NotificationCenter.default
.addObserver(self,
selector: #selector(keyboardWillChange(_:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
}
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default
.removeObserver(self,
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil)
NotificationCenter.default
.removeObserver(self,
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
NotificationCenter.default
.removeObserver(self,
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
}
@objc private func keyboardWillChange(_ notification: NSNotification) {
guard
let delegate = self as? KeyboardChangeDelegate,
let info = notification.userInfo,
let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let kb = view.convert(kbFrame, from: view.window!.screen.coordinateSpace)
let fromBottom = max(0, view.frame.size.height - kb.origin.y)
delegate.doKeyboardAnimateTo(toValue: fromBottom)
view.layoutIfNeeded()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment