Last active
January 30, 2019 00:03
-
-
Save alexpaul/97f879125d779a073b761bb40e417b98 to your computer and use it in GitHub Desktop.
Setting up keyboard notifications and responding to their actions
This file contains hidden or 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
| // | |
| // ViewController.swift | |
| // KeyboardHandling | |
| // | |
| // Created by Alex Paul on 1/29/19. | |
| // Copyright © 2019 Alex Paul. All rights reserved. | |
| // | |
| import UIKit | |
| class ViewController: UIViewController { | |
| @IBOutlet weak var containerView: UIView! | |
| @IBOutlet weak var usernameTextField: UITextField! | |
| @IBOutlet weak var passwordTextField: UITextField! | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| registerForKeyboardNotifications() | |
| } | |
| private func registerForKeyboardNotifications() { | |
| NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) | |
| NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) | |
| } | |
| private func unregisterForKeyboardNotifications() { | |
| NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) | |
| NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) | |
| } | |
| override func viewWillDisappear(_ animated: Bool) { | |
| super.viewWillDisappear(true) | |
| unregisterForKeyboardNotifications() | |
| } | |
| @objc private func keyboardWillShow(notification: NSNotification) { | |
| guard let info = notification.userInfo, | |
| let frame = info["UIKeyboardFrameEndUserInfoKey"] as? CGRect else { | |
| return | |
| } | |
| print(info) // prints keys in info dictionary e.g UIKeyboardFrameEndUserInfoKey | |
| containerView.transform = CGAffineTransform(translationX: 0, y: -frame.height) | |
| } | |
| @objc private func keyboardWillHide(notification: NSNotification) { | |
| containerView.transform = CGAffineTransform.identity | |
| } | |
| @IBAction func loginButtonPressed(_ sender: UIButton) { | |
| usernameTextField.resignFirstResponder() | |
| passwordTextField.resignFirstResponder() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment