我的ViewController上有两个UItext字段。第一个在ViewController的上半部分,但第二个在底部。
我已经设法让键盘在返回时隐藏起来,但是,当我点击第二个(较低的)UItextField时,键盘出现并覆盖它。这意味着不再可能看到您正在键入的内容。
如何在单击第二个 UItextField 时向上移动视图控制器,以便用户可以看到他们正在键入的内容,然后在用户按 Return 键时将视图控制器移回?
使用scrollView并在显示键盘时滚动文本字段
在您的孔视图(ViewController视图)中添加scrollView,然后添加隐藏和显示键盘的通知
当键盘显示时,通过减去键盘hide:scrollView.ContentInset.height-keyboard.height来更改scrollView内容插入:
func registerForKeyboardNotifications() {
//Adding notifies on keyboard appearing
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIWindow.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIWindow.keyboardWillHideNotification, object: nil)
}
@objc
func keyboardWillShow(notification: NSNotification) {
guard let keyboareRect = notification.userInfo?[UIWindow.keyboardFrameBeginUserInfoKey] as? CGRect else { return }
let keyboardSize = keyboareRect.size
let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
var aRect = self.view.frame
aRect.size.height -= keyboardSize.height
guard let activeTextField = self.activeTextField else { return }
if !aRect.contains(activeTextField.frame.origin) {
scrollView.scrollRectToVisible(activeTextField.frame, animated: true)
}
}
@objc
func keyboardWillHide(notification: NSNotification) {
scrollView.contentInset = UIEdgeInsets.zero
scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}