Search code examples
iosswiftkeyboardsubview

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?


Solution

    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.