我在UITextField
中嵌入了UIScrollView
。当键盘出现时,文本字段被键盘隐藏。
[我使用以下代码为UIResponder.keyboardWillShowNotification
和UIResponder.keyboardWillHideNotification
设置观察者,并相应地设置contentInset
的UIScrollView
。
extension ViewController {
func addKeyboardNotificationsObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillBeShown(notification:)),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillBeHidden(notification:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
@objc func keyboardWillBeShown(notification: NSNotification) {
guard
let kbRect = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber,
let curve = notification.userInfo?[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
else { return }
let insets = UIEdgeInsets(top: 0, left: 0, bottom: kbRect.height, right: 0)
UIView.animate(
withDuration: duration.doubleValue,
delay: .zero,
options: .init(rawValue: curve.uintValue << 16),
animations: {
self.scrollView.contentInset = insets
self.scrollView.scrollIndicatorInsets = insets
},
completion: nil
)
}
@objc func keyboardWillBeHidden(notification: NSNotification) {
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
}
}
该代码有效。但是,当键盘出现时,文本字段会暂时被部分隐藏。文本字段似乎在动画结尾附近跳起来。
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS80UzNIcS5naWYifQ==” alt =“键盘的GIF向上移动”>
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS95VVBsdS5naWYifQ==” alt =“键盘在慢动作中向上移动的GIF”>“>
[谁能指出解决此问题的方法,以使文本字段与即将出现的键盘同步向上移动,并且在动画快结束时不会显示为向上跳跃?
我在UIScrollView中嵌入了一个UITextField。当键盘出现时,文本字段被键盘隐藏。我使用以下代码为UIResponder设置观察者。...
pod'IQKeyboardManagerSwift','6.3.0'
首先,您无需安装任何吊舱即可正常工作。