繁体   English   中英

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

[英]Move Button & View when Keyboard Appears in Swift

我试图移动最初位于视图底部的按钮,但是当选择了文本字段并渲染了键盘时,将按钮随其向上移动。

如果您使用过应用程序Robinhood,则在登录或注册时其功能相同。

其他几篇文章都无法为我解决此问题。

使用Swift使用键盘移动视图

是否有已经解决此功能的外部存储库或解决方案?

  1. 首先,将以下代码写入ui视图扩展。

扩展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. 然后像我下面使用的那样使用该功能。

    覆盖func viewDidLoad(){

      super.viewDidLoad() yourButtonName.bindToKeyboard() } 

希望这将是适合您的解决方案。

暂无
暂无

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

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