Skip to content

Instantly share code, notes, and snippets.

@uy
Created October 14, 2018 11:29
Show Gist options
  • Save uy/783ab5bbeeea84a5a4288d12384b05a3 to your computer and use it in GitHub Desktop.
Save uy/783ab5bbeeea84a5a4288d12384b05a3 to your computer and use it in GitHub Desktop.
Move a view up only when the keyboard covers an input field
class Welcome: UIViewController {
@IBOutlet weak var tfEMail: TextField!
@IBOutlet weak var tfPassword: TextField!
private var activeTextField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
registerForKeyboardNotifications()
}
override func viewDidDisappear(_ animated: Bool) {
deregisterFromKeyboardNotifications()
super.viewDidDisappear(animated)
}
}
private extension Welcome {
func setupUIComponents() {
tfEMail.tfText.returnKeyType = .done
tfPassword.tfText.returnKeyType = .done
tfEMail.tfText.delegate = self
tfPassword.tfText.delegate = self
}
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func deregisterFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
let info: Dictionary = notification.userInfo!
if let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
if let activeTextField = activeTextField {
let realActiveTextFieldFrame = activeTextField.convert(activeTextField.frame, to: self.view)
let textFieldHeightDiff = realActiveTextFieldFrame.origin.y + realActiveTextFieldFrame.height
let keyboardHeightDiff = self.view.frame.height - keyboardSize.height
let viewMoveDiff = keyboardHeightDiff - textFieldHeightDiff
if viewMoveDiff < 0 {
self.view.transform = CGAffineTransform(translationX: 0, y: viewMoveDiff)
}
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
self.view.transform = CGAffineTransform.identity
}
}
extension Welcome: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeTextField = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
}
@hasmikh0
Copy link

Thanks a lot! This code really helped me)

@uy
Copy link
Author

uy commented Feb 26, 2022

Your message give me motivation :) Me thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment