当键盘出现在 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.
如果您使用过 Robinhood 应用程序,则其在登录或注册时具有相同的功能。
其他几个帖子都无法为我解决这个问题。
Move view with keyboard using Swift
是否有已经解决此功能的外部回购或解决方案?
- 首先将下面的代码写入 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)
}
}
然后像我在下面使用的那样使用那个函数。
覆盖 func viewDidLoad() {
super.viewDidLoad()
yourButtonName.bindToKeyboard()
}
希望这是适合您的解决方案。
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
是否有已经解决此功能的外部回购或解决方案?
- 首先将下面的代码写入 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)
}
}
然后像我在下面使用的那样使用那个函数。
覆盖 func viewDidLoad() {
super.viewDidLoad() yourButtonName.bindToKeyboard() }
希望这是适合您的解决方案。