Last active
October 9, 2019 07:32
-
-
Save erdemildiz/7aeb71709651cec96d8dc3dffc766518 to your computer and use it in GitHub Desktop.
IOS TextField Keyboard Problem on Swift [Swift 4.2.1]
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
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