Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple extension for handling keyboard shows/hides
//
// KeyboardListener.swift
//
// Created by Patrick B. Gibson on 7/16/16.
//
import UIKit
protocol KeyboardListener: AnyObject {
var view: UIView! { get }
// The constraint in your view controller which controls the height of the view the underneath the keyboard.
var topViewHeightConstraint: NSLayoutConstraint! { get }
}
extension KeyboardListener {
// Called from viewDidLoad to set things up
func addKeyboardObservers() {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillShowNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: keyboardWillShow)
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardDidShowNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: keyboardDidShow)
}
func keyboardWillShow(notification: NSNotification) {
let info = notification.userInfo
let value = info?[UIKeyboardFrameEndUserInfoKey] as? NSValue
if let keyboardHeight = value?.CGRectValue().size.height {
topViewHeightConstraint.constant = view.bounds.height - keyboardHeight
}
}
func keyboardDidShow(notification: NSNotification) {
let info = notification.userInfo
let value = info?[UIKeyboardFrameEndUserInfoKey] as? NSValue
if let keyboardHeight = value?.CGRectValue().size.height {
topViewHeightConstraint.constant = view.bounds.height - keyboardHeight
UIView.animateWithDuration(0.2, animations: {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment