首页 > 解决方案 > 单击tableView中的文本字段时,ScrollView没有向上移动

问题描述

我试过这段代码:在 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 内的文本字段并记录它时,总是检测到“键盘出现”。

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

标签: iosswifttableviewscrollviewtextfield

解决方案


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

pod 'TPKeyboardAvoiding'

如果您使用情节提要,请将 tableView 基类设置为TPKeyboardAvoidingTableView.


推荐阅读