I have a view which contains 4 textfields and a button .. this view is not the main view .. the problem is that the keyboard covers the textfields down and the button!
i tried this code but its not working:
// Move the text field in a pretty animation!
func moveTextField(_ textField: UITextField, moveDistance: Int, up: Bool) {
let moveDuration = 0.3
let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
if textField.tag>=2{
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()}
}
and i have set the tag numbers for them from 0 to 4...
and i have set the delegate in viewDidLoad:
fname.delegate=self
email.delegate=self
mobile1.delegate=self
mobile2.delegate=self
but this didn't work still the keyboard will cover the textfields down and the button! why? and how to solve it?
UPDATE:
I think i figured out the problem ... i tried this:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
@objc func keyboardWillChange(notification: Notification){
guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{
return
}
if activeTF.tag >= 2 {
if notification.name == Notification.Name.UIKeyboardDidShow || notification.name == Notification.Name.UIKeyboardDidChangeFrame {
view.frame.origin.y = -keyboardRect.height
}else{
view.frame.origin.y = 0
}
}
}
with:
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
both funcs works perfectly... but when i change it to:
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
//do not add a line break
return false
}
only the maketextfieldreturn will work and keyboardwillchange will not work! Why?