ios - 当某些特定的文本字段被键盘隐藏时,如何向上移动表格视图?
问题描述
我在表格视图单元格中有一个带有文本字段的表格视图。当我尝试在表格视图底部的文本字段中输入文本时,文本字段会被键盘隐藏。我试图通过使用下面的代码来解决这个问题。
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
@objc func keyBoardWillChange(notification : Notification)
{
print("Keyboard will show :\(notification.name.rawValue)")
let cell = deliveryTableView.cellForRow(at: IndexPath.init(row: 8, section: 0))
view.frame.origin.y = -175
}/*
@objc func KeyBoardWillHide(notification : Notification)
{
UIView.animateKeyframes(withDuration: 0.25, delay: 0.0, options: UIView.KeyframeAnimationOptions.allowUserInteraction, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
}, completion: nil)
}*/
deinit {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
但问题是即使单击第一个文本字段,表格视图也会向上移动,这看起来不太好。但我希望表格视图仅在底部存在文本字段的情况下向上移动。
解决方案
在 appdelegate 中使用IQKeyboardManager,只需一行代码。它将处理键盘。
步骤 1)在 pod-file 中添加 pod 'IQKeyboardManager' 并运行pod install
步骤2) 通过在appdelegate的didFinishLaunchingWithOptions方法中编写这段代码来启用IQKeyboardManager
IQKeyboardManager.shared.enable = true