1

I am trying to move a button that is initially at the bottom of the view, but when a text field is selected and the keyboard rendered, move the button up with it.

If you have used the app Robinhood, its the same functionality when signing in or signing up.

Several other posts have not been able to solve this for me.

Move view with keyboard using Swift

Is there an external repo or solution that has already solved this feature?

2

1 Answer 1

4
  1. First of write the below code into the ui view extension.

extension UIView {

func bindToKeyboard() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}

@objc func keyboardWillChange(_ notification: NSNotification) {
    let duration = notification.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
    let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! UInt
    let begginingFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let endFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let deltaY = endFrame.origin.y - begginingFrame.origin.y

    UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
        self.frame.origin.y += deltaY
    }, completion: nil)
}

}

  1. Then use that function like i have used below.

    override func viewDidLoad() {

        super.viewDidLoad()
        yourButtonName.bindToKeyboard()
    }
    

Hope it will be the right solution for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to make the duration infinite? When I click on a text view the button moves with the keyboard, but as soon as I start to type the button disappears which I am assuming its going back to its original position under the keyboard.
Is there a way to make the duration infinite? When I click on a text view the button moves with the keyboard, but as soon as I start to type the button disappears which I am assuming its going back to its original position under the keyboard.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.