当键盘在iOS中与UITextField重叠时,我正在使用以下代码来解决常见问题:
@IBOutlet var scrollView: UIScrollView!
var activeField: UITextField?
override func viewWillAppear(_ animated:Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
}
键盘通知
func keyboardWillHide(_ notification: Notification) {
var info = notification.userInfo!
let keyboardSize = info[UIKeyboardFrameEndUserInfoKey] as? CGRect
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height , 0.0)
scrollView.contentInset = contentInsets
}
func keyboardWillShow(_ notification: Notification) {
var info = notification.userInfo!
let keyboardSize = info[UIKeyboardFrameEndUserInfoKey] as? CGRect
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height + 8, 0.0)
scrollView.contentInset = contentInsets
}
它就像魔术一样。
但是我面临以下问题。在文本编辑后隐藏键盘时,视图将返回到之前的状态,应该是这样,但是滚动被禁用。我不知道为什么。我设置了scrollView.isScrollEnabled = true
,但是它不能解决我的问题。
我该如何摆脱呢?
答案 0 :(得分:1)
此行是错误的(嗯,整个事情是错误的,但这是您抱怨的特定行):
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
更好的
let contentInsets: UIEdgeInsets = .zero
更好的是,当键盘显示时,保存内容插图。隐藏时,将它们还原为您保存的值。