键盘出现时向上移动视图

问题:

我有一个ViewController ,它有一个UIScrollView的子类。

在scrollView中有3个UITextField 。 其中2个使用数字键盘,1个使用UIPickerView键盘。

问题是当键盘出现时,它隐藏了UITextField 。 所以我想要做的就是当键盘被显示时移动UIViewController的视图。

我已经尝试过了:

我已经search了这个问题,所以我发现了一些答案,基于他们我写这个代码:

 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

在全球范围内build立和运作已经非常简单。

您需要根据键盘隐藏设置高度。 有四个可用的键盘观察员。

 1) UIKeyboardWillShow 2) UIKeyboardDidShow 3) UIKeyboardWillHide 4) UIKeyboardDidHide 

你需要注册键盘观察者:

 NotificationCenter.default.addObserver(self, selector: #selector(keyboardShowNotification), name:NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardHideNotification), name:NSNotification.Name.UIKeyboardWillHide, object: nil) 

这里是方法观察者方法:

 func keyboardShowNotification(notification:NSNotification){ var userInfo = notification.userInfo! var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) var contentInset:UIEdgeInsets = YOUR_SCROLLVIEW_OBJ.contentInset contentInset.bottom = keyboardFrame.size.height YOUR_SCROLLVIEW_OBJ.contentInset = contentInset } func keyboardHideNotification(notification:NSNotification){ let contentInset:UIEdgeInsets = UIEdgeInsets.zero YOUR_SCROLLVIEW_OBJ = contentInset } 

处理键盘的另一个最好的关键是IQKeyboardManager 。 您只需将它们添加到您的应用程序,它将处理一切。