我有一个 tableView,在第 0 行有一个 textField,在第 3 行有一个 textView。我的 tableview 目前每次出现键盘时都会向上滑动。当 tableView 向上滑动时,您看不到第 0 行中的 textField。如何为第 0 行禁用此功能并仅保留第 3 行?我尝试使用 Protocol & Delegates 来尝试只为第 3 行封装函数,但这不起作用。
类 CreateEditItemController: UIViewController, CreateItemDescriptionCellDelegate {
@IBOutlet weak var tableView: UITableView!
func handleKeyboardShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
//self.view.frame.origin.y -= keyboardSize.height
self.view.frame.origin.y -= 200
}
}
}
func handleKeyboardHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
...
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "CreateItemDescriptionCell", for: indexPath) as! CreateItemDescriptionCell
cell.delegate = self
return cell
default:
return tableView.cellForRow(at: indexPath)!
}
}
}
protocol CreateItemDescriptionCellDelegate: class {
func handleKeyboardShow(notification: NSNotification)
func handleKeyboardHide(notification: NSNotification)
}
class CreateItemDescriptionCell: UITableViewCell, UITextViewDelegate {
//IBOUTLETS
@IBOutlet weak var notesTextView: UITextView!
weak var delegate: CreateItemDescriptionCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
notesTextView.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func handleKeyboardShow(notification: NSNotification) {
delegate?.handleKeyboardShow(notification: notification)
}
@objc func handleKeyboardHide(notification: NSNotification) {
delegate?.handleKeyboardHide(notification: notification)
}
}
最佳答案
经过一些数学运算后,您尝试做的事情是可能的,但我建议为此使用第三方 pod,而不是在 evert Controller 上手动执行此操作。
将此添加到您的 pod 文件中:
# IQKeyboardManager: Codeless drop-in universal library allows to prevent issues of keyboard sliding up
# https://github.com/hackiftekhar/IQKeyboardManager
pod 'IQKeyboardManagerSwift'
更多详细信息和文档 View : https://github.com/hackiftekhar/IQKeyboardManager
你唯一需要写的行是:
// Enabling IQKeyboardManager
IQKeyboardManager.shared.enable = true
在
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
这将解决您所有的问题,您无需计算帧数或任何其他内容。
关于swift - 当键盘存在时,选择导致 View 向上滑动的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55561143/