问题:
我有一个ViewController
有一个子类UIScrollView
in it.
在scrollView中有3个UITextField
s。其中 2 个带有数字键盘,1 个带有UIPickerView
键盘。
问题是当键盘出现时,它会隐藏UITextField
s。所以我想做的就是移动UIViewController
显示键盘时,视图向上。
我已经尝试过的:
我在 SO 上搜索了这个问题,找到了一些答案,根据它们我写了这段代码:
override func viewDidLoad() {
super.viewDidLoad()
//Keyboard notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//MARK: - keyboards
@objc fileprivate func keyboardWillShow(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
@objc fileprivate func keyboardWillHide(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
if self.controllerContentView.frame.origin.y == 0 {
self.controllerContentView.frame.origin.y = -keyboardSize.height
} else {
self.controllerContentView.frame.origin.y = 0
}
})
}
}
fileprivate func dismissKeyboard() {
self.view.endEditing(true)
}
//Touch handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismissKeyboard()
}
我尝试过的问题:
有时效果很好,但有时视图会“跳”回来/“跳”下来,我不明白为什么。
有人发现我的代码有任何可能导致此错误的问题吗?
谢谢你!
我使用名为 IQKeyboardManager 的 CocoaPod。
https://github.com/hackiftekhar/IQKeyboardManager https://github.com/hackiftekhar/IQKeyboardManager
它的设置非常简单,并且可以在全球范围内使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)