Move Button & View when Keyboard Appears in Swift

五迷三道 提交于 2020-01-05 05:46:17

问题


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?


回答1:


  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.



来源:https://stackoverflow.com/questions/53000282/move-button-view-when-keyboard-appears-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!