Created
February 14, 2017 17:01
-
-
Save brunoguerios/579309cdddec3e0047388c0ba0904c6d to your computer and use it in GitHub Desktop.
KeyboardController handles the most common case of UI update required when the keyboard is presented on iOS. It updates the view's bottom constraint to match the top of the keyboard frame.
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
// | |
// KeyboardController.swift | |
// | |
// Created by Bruno Guerios on 2017-02-13. | |
// | |
import Foundation | |
import UIKit | |
class KeyboardController: NSObject { | |
var viewController: UIViewController | |
var constraint: NSLayoutConstraint | |
var isKeyboardHidden: Bool { | |
return constraint.constant == 0 | |
} | |
// MARK: Life Cycle | |
init(viewController: UIViewController, constraint: NSLayoutConstraint) { | |
self.viewController = viewController | |
self.constraint = constraint | |
super.init() | |
self.setupKeyboardObservers() | |
} | |
// MARK: Setup | |
private func setupKeyboardObservers() { | |
self.setupKeyboardWillChangeObserver() | |
self.setupDismissKeyboardTapGestureRecognizer() | |
} | |
private func setupKeyboardWillChangeObserver() { | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: .UIKeyboardWillChangeFrame, object: nil) | |
} | |
private func setupDismissKeyboardTapGestureRecognizer() { | |
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) | |
tap.delegate = self | |
viewController.view.addGestureRecognizer(tap) | |
} | |
// MARK: Private | |
func keyboardWillChange(_ notification: Notification) { | |
guard let info = notification.userInfo else { return } | |
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue | |
constraint.constant = UIScreen.main.bounds.size.height - keyboardFrame.origin.y | |
let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval | |
UIView.animate(withDuration: duration, animations: { | |
self.viewController.view.layoutIfNeeded() | |
}) | |
} | |
func dismissKeyboard() { | |
viewController.view.endEditing(true) | |
} | |
} | |
extension KeyboardController: UIGestureRecognizerDelegate { | |
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { | |
return !isKeyboardHidden | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment