【问题标题】:Move Button & View when Keyboard Appears in SwiftSwift 中出现键盘时移动按钮和视图
【发布时间】:2019-03-30 17:10:46
【问题描述】:

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.

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

其他几个帖子无法为我解决这个问题。

Move view with keyboard using Swift

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

【问题讨论】:

标签: ios swift keyboard subview


【解决方案1】:
  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()
    }
    

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

【讨论】:

  • 有没有办法让持续时间无限?当我单击文本视图时,按钮会随键盘移动,但一旦我开始键入按钮就会消失,我假设它会回到键盘下方的原始位置。
  • 有没有办法让持续时间无限?当我单击文本视图时,按钮会随键盘移动,但一旦我开始键入按钮就会消失,我假设它会回到键盘下方的原始位置。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 2017-01-08
  • 2010-12-19
  • 2018-05-21
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多