这个问题可以通过使用滚动视图或者调整键盘的高度来解决。
假设你的文本输入框位于一个ScrollView里面,可以在点击输入框触发事件后,将ScrollView的contentOffset设置为输入框的底部位置,这样当键盘出现后,ScrollView会自动滚动到合适的位置。
可以先定义一个变量来保存当前激活的输入框:
var activeField: UITextField?
然后设置每一个输入框触发事件:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
// 注册每一个输入框的事件
for textField in textFields {
textField.delegate = self
textField.addTarget(self, action: #selector(textFieldDidBeginEditing(_:)), for: UIControl.Event.editingDidBegin)
textField.addTarget(self, action: #selector(textFieldDidEndEditing(_:)), for: UIControl.Event.editingDidEnd)
}
}
@objc fileprivate func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
@objc fileprivate func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
}
接下来,在键盘出现时,我们可以根据输入框的位置和键盘的高度来动态调整ScrollView的contentOffset:
@objc private func keyboardWillShow(notification: NSNotification) {
guard let keyboardFrameValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue,
let activeField = activeField else {
return
}
let keyboardHeight = keyboardFrameValue.cgRectValue.size.height
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
var frame = scrollView.frame
frame.size.height -= keyboardHeight
if !frame.contains(activeField.frame.origin) {
let scrollViewOffset = CGPoint(x: 0, y: activeField.frame.origin.y - keyboardHeight)
scrollView.setContentOffset(scrollViewOffset, animated: true)
}
}
当键盘隐藏时,我们需要将ScrollView的contentInset还原:
@objc private func keyboardWillHide(notification: NSNotification) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
这样就可以解决键盘遮挡输入框的问题了。当然,你也可以选择调整键盘的高度来适应输入框的位置,在应用中实现的方式可能会有所不同,但总体思路是一致的。