简体   繁体   English

在Swift中出现键盘时移动按钮和查看

[英]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. 如果您使用过应用程序Robinhood,则在登录或注册时其功能相同。

Several other posts have not been able to solve this for me. 其他几篇文章都无法为我解决此问题。

Move view with keyboard using Swift 使用Swift使用键盘移动视图

Is there an external repo or solution that has already solved this feature? 是否有已经解决此功能的外部存储库或解决方案?

  1. First of write the below code into the ui view extension. 首先,将以下代码写入ui视图扩展。

extension UIView { 扩展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() { 覆盖func viewDidLoad(){

      super.viewDidLoad() yourButtonName.bindToKeyboard() } 

Hope it will be the right solution for you. 希望这将是适合您的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM