Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Last active October 9, 2019 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erdemildiz/7aeb71709651cec96d8dc3dffc766518 to your computer and use it in GitHub Desktop.
Save erdemildiz/7aeb71709651cec96d8dc3dffc766518 to your computer and use it in GitHub Desktop.
IOS TextField Keyboard Problem on Swift [Swift 4.2.1]
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(UIResponder.keyboardWillShowNotification)
NotificationCenter.default.removeObserver(UIResponder.keyboardWillHideNotification)
NotificationCenter.default.removeObserver(UIResponder.keyboardWillChangeFrameNotification)
}
@objc func keyboardWillChange(notification: Notification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
if notification.name == UIResponder.keyboardWillChangeFrameNotification || notification.name == UIResponder.keyboardWillShowNotification {
view.frame.origin.y = -keyboardSize.height
} else {
view.frame.origin.y = 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment