【问题标题】:UITableView Scrolls automatically while textfield begins editingUITableView 在文本字段开始编辑时自动滚动
【发布时间】:2026-02-19 23:00:02
【问题描述】:

我正在开发一个 iOS 应用程序,它具有不同的表单,根据用户选择填充到 UITableview 中。每个表单都有不同的字段,例如 Textfield、DatePicker、PickerView。所以我使用一个 TableViewCell (nib) 来保存所有这些并根据问题显示或隐藏项目。 定义了保存函数,当用户输入数组时将保存值。

我的问题是,有时我的 tableview 滚动,好像索引失控了。就像当我选择任何文本字段时,Tableview 滚动到顶部。我已经删除了所有键盘观察器方法并检查过,它仍然在发生。

下面是我的保存功能代码:

 func saveFormValue(mystr: String) {
    //selectedIndex is a global variable (NSIndexPath)
    let dict = sections[selectedIndex!.section].questions![selectedIndex!.row]
    dict.answer = mystr
    sections[selectedIndex!.section].questions![selectedIndex!.row] = dict
    let answer = updated_answer.init(ID: ID, form_id: selected_form_id, form_name: formName, section_id: dict.section_id ?? "",question_id: dict.question_id ?? "", question_name: dict.question_name!,question_type:dict.question_type!)

    updatedArray.append(answer)
    self.tableView.reloadData()
}

这是 textfieldDidBeginEditing 函数中的代码(如何初始化 selectedIndexPath):

 guard let index = tableView.indexPath(for: cell) else {
    return
 }
 selectedIndex = index as NSIndexPath

我已经为单元格添加了委托,我注意到的一件事是,每当我按一次pickerview 或 datepicker 时,就会发生这个问题。如果我只触摸 textField 单元格,我看不到这个问题。

请让我知道任何进一步的细节。

【问题讨论】:

  • 您是否正确管理键盘处理?键盘出现后您的文本字段可见吗?
  • @gauravbajaj 我添加了键盘观察器功能并检查,它工作正常。这个问题有时会发生。例如:在我的表格视图中,我有 30 个问题。我向下滚动到第 20 个问题并按下该单元格的文本字段,此时键盘出现,但 tableview 滚动到其他单元格的顶部。
  • 分享你的键盘观察功能。

标签: ios swift uitableview


【解决方案1】:

试试这个代码,希望对你有帮助。

 if let thisIndexPath = tableView.indexPath(for: cell) {
    tableView.scrollToRow(at: thisIndexPath, at: .top, animated: false)
 }

【讨论】:

    【解决方案2】:

    在文本字段委托方法textFieldDidBeginEditing 上使用以下代码:

    func textFieldDidBeginEditing(_ textField: UITextField) {
            let indexParh = NSIndexPath(row: textField.tag, section: 0)
            self.constTBL_Bottom.constant = 260
            self.tblViewObj.scrollToRow(at: indexParh as IndexPath, at: .middle, animated: false)
        }
    

    您还需要管理表格底部常量。当您辞去键盘时,将表格视图常量设置为 0

    希望这会奏效:)

    【讨论】: