There are several TextFields in a UIView.I want move view up when user edit TextField.And then i try it reference Move view with keyboard using Swift
My core code is below:
//MARK: Properties
@IBOutlet weak var userAccountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
//MARK: Callback
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
if self.view.frame.origin.y == 0{
//self.view.frame.origin.y -= keyboardSize.height
self.view.frame.origin.y -= 150
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
if self.view.frame.origin.y != 0{
//self.view.frame.origin.y += keyboardSize.height
self.view.frame.origin.y += 150
}
}
}
There are two issues:
1.The keyboardSize.height with hide the keyboard is bigger than keyboardSize.height with show the keyboard.Then there will be a black field top after the keyboard hide. So now i must use a constant number.
2.The view move up after the keyboard show, it's good.But the view move down again when i type some chars or i click other TextFiled.It's good If i put these TextFields into a ScrollView.But i don't it's why.Like below picture: enter image description here
Any help would be greatly appreciated.