Last active
February 21, 2018 22:55
-
-
Save patr1ck/1bf98b1120df8d63362bb3fb7e9ccabd to your computer and use it in GitHub Desktop.
A simple extension for handling keyboard shows/hides
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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