UITableView在文本字段开始编辑时自动滚动

时间:2019-03-20 10:19:57

标签: ios swift uitableview

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

我的问题是,有时我的表视图会滚动,就像索引失去控制一样。就像我选择任何文本字段时一样,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单元,就看不到此问题。

请让我知道更多详细信息。

2 个答案:

答案 0 :(得分:0)

尝试此代码,希望对您有所帮助。

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

答案 1 :(得分:0)

在文本字段委托方法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

希望这会起作用:)