Hi,
I need to move the controller up so fields are not hidden by keyboard.
So I use textfield and textview delegate methods to achieve this.
Here is the code, but it is repetitive.
Is there any way to make it less repetitive?
I need to move the controller up so fields are not hidden by keyboard.
So I use textfield and textview delegate methods to achieve this.
Here is the code, but it is repetitive.
Is there any way to make it less repetitive?
Code Block func textFieldDidBeginEditing(_ textField: UITextField) { self.view.setNeedsLayout() UIView.animate(withDuration: 0.2, animations: { self.view.center.y -= 150 }, completion: { finished in }) } func textFieldDidEndEditing(_ textField: UITextField) { self.view.setNeedsLayout() UIView.animate(withDuration: 0.2, animations: { self.view.center.y += 150 }, completion: { finished in }) } func textViewDidBeginEditing(_ textField: UITextView) { self.view.setNeedsLayout() UIView.animate(withDuration: 0.2, animations: { self.view.center.y -= 150 }, completion: { finished in }) } func textViewDidEndEditing(_ textField: UITextView) { self.view.setNeedsLayout() UIView.animate(withDuration: 0.2, animations: { self.view.center.y += 150 }, completion: { finished in }) }
You could also group both actions in a single one, if tou define a property in the class : private var viewMoved = false
And connect the beginEditing and endEditing events for both TextField and TextView to this IBAction.
However, I do not recommend such a design, harder to understand.
Code Block @IBAction func beginEditing(_ sender: Any) { self.view.setNeedsLayout() UIView.animate(withDuration: 0.2, animations: { self.view.center.y += self.viewMoved ? -150 : 150 }, completion: { finished in self.viewMoved.toggle() }) }
And connect the beginEditing and endEditing events for both TextField and TextView to this IBAction.
However, I do not recommend such a design, harder to understand.