0

I have searched pretty much everywhere and can't find a solution for this. So i have a log in screen and when the keyboard shows the textfields move up for readability. However as soon as I type or switch to a different textfield the fields jump back to their original position...

Here is the code

override func viewDidLoad() {
    super.viewDidLoad()

    usernameField.delegate = self

    passwordField.delegate = self
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()

    return true
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.animateTextField(textField: textField, up:true)
}

func textFieldDidEndEditing(_ textField: UITextField) {

    self.animateTextField(textField: textField, up:false)
}

func animateTextField(textField: UITextField, up: Bool)
{
    let movementDuration: Double = 0.3

    var labelMove: CGFloat = -20
    var userMove: CGFloat = -40
    var passMove: CGFloat = -50

    if up
    {
        labelMove = -20
        userMove = -40
        passMove = -50
    }
    else
    {
        labelMove = 20
        userMove = 40
        passMove = 50
    }
    UIView.beginAnimations("animateTextField", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)
    self.titleLabel.frame = self.titleLabel.frame.offsetBy(dx: 0, dy: labelMove)
    self.usernameField.frame = self.usernameField.frame.offsetBy(dx: 0, dy: userMove)
    self.passwordField.frame = self.passwordField.frame.offsetBy(dx: 0, dy: passMove)
    UIView.commitAnimations()
}

Please help?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    You should use scroll view to do that. There are plenty of examples available on internet. Your approach is wrong and will barely work on one device type, not at all in all devices types. – GIJOW Dec 07 '17 at 15:54
  • Check out my answer: https://stackoverflow.com/questions/47698632/move-view-up-when-keyboard-is-presented/47699644#47699644 – Nirmalsinh Rathod Dec 07 '17 at 16:41
  • You can use IQKeyboardManager. it will help you most in keyboard case. – Nirmalsinh Rathod Dec 07 '17 at 16:42
  • use IQKeyboardManager : https://github.com/hackiftekhar/IQKeyboardManager – Kuldeep Dec 07 '17 at 19:54

1 Answers1

0

You should add these on an UIScrollView and not animate them Up/Down.

Inside of the delegates DidBeginEditing and DidEndEditing, you scroll up and down inside of the UIScrollView respectively.

The reason why your issue is happening is because as soon as you start the second animation, the position of the Textfields reset to the original position defined (since you defined an animation not set a new origin for the textfields)

Hope this helps!

AshvinGudaliya
  • 3,234
  • 19
  • 37
Mohamad Bachir Sidani
  • 2,077
  • 1
  • 11
  • 17