单击 tableView 中的文本字段时,ScrollView 没有向上移动

ScrollView did not move up when click textfield inside tableView

我试过这段代码: 在 viewWillAppear 中:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

和:

@objc func keyboardWillAppear(notification:NSNotification) {
    print("keyboard appear")
    var info = notification.userInfo
    let keyBoardSize = info![UIKeyboardFrameEndUserInfoKey] as! CGRect
    scrollCreateEditContact.contentInset = UIEdgeInsetsMake(0.0, 0.0, keyBoardSize.height, 0.0)
    scrollCreateEditContact.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, keyBoardSize.height, 0.0)
}

@objc func keyboardWillDisappear(notification:NSNotification) {
    print("keyboard disappear")
    scrollCreateEditContact.contentInset = UIEdgeInsets.zero
    scrollCreateEditContact.scrollIndicatorInsets = UIEdgeInsets.zero
}

结果是:

我想要的是当键盘出现时,文本字段没有被键盘覆盖:

该代码仅适用于不在 tableView 内的文本字段。 但是当我在 tableView 中单击文本字段并记录它时 "keyboard appear" 总是检测到。

当键盘出现时,tableView 中的文本字段未被键盘覆盖的正确代码是什么?

这是常见行为,ios 无法自动调整键盘上方的内容,这与 android 不同。我的解决方案是,您可以将所有视图(照片、文本字段等)包装在 tableView 中。并使用 TPKeyboardAvoiding 库。

pod 'TPKeyboardAvoiding'

如果使用 Storyboard,请将 tableView base-class 设置为 TPKeyboardAvoidingTableView

以下是用于管理此类行为的最常见和最常用的库:

  1. TPKeyboardAvoiding
  2. IQKeyboardManager

您也可以通过 CocoaPods 安装它们。

处理这个问题最简单的方法是为 IQKeyboardManager 安装 pod:

通过 cocoa 安装 pods:

pod 'IQKeyboardManagerSwift'

用法:

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

      IQKeyboardManager.shared.enable = true

      return true
    }
}

有关 IQKeyboardManager 的更多信息,请参阅此 link:

https://github.com/hackiftekhar/IQKeyboardManager