Baily
Baily

Reputation: 1380

Move Button & View when Keyboard Appears in Swift

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?

Upvotes: 1

Views: 2010

Answers (1)

Ahemadabbas Vagh
Ahemadabbas Vagh

Reputation: 494

  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.

Upvotes: 4

Related Questions