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?

Baily
  • 1,290
  • 2
  • 14
  • 35

1 Answers1

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.

Ahemadabbas Vagh
  • 492
  • 3
  • 15
  • 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. – Baily Nov 02 '18 at 18:53
  • 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. – Hadiseh Apr 22 '20 at 06:56