Swift 2.1 - 删除单元格后清除 TableViewCell 中的文本字段

Swift 2.1 - Clear textfield in TableViewCell after cell is deleted

我有一个用于添加食谱说明(步骤)的 TableView。给出第一个单元格,用户可以根据需要添加更多单元格。 并且用户可以删除他们不需要的单元格。

每个单元格(行)都配置了一个用于说明文本内容的 UITextfield 和一个用于标记说明顺序的 UILabel。

一个可能的用例可能是用户在单元格中键入了一些文本并决定删除它以重新开始。当用户按下 添加步骤 按钮时,用户将看到一个新的单元格,但之前的文本已填写。 为了防止这种情况,我有 cell.stepTextField.text = "" 这样用户可以获得一个带有清晰文本字段的单元格。

它有点管用,但是当我尝试许多可能的交互时,我得到了有趣的结果,如所附的屏幕截图。在那个示例屏幕截图中,我丢失了第一个单元格中的指令,即使我没有删除这个单元格。

如何确保用户每次都能获得干净的文本字段并且不会丢失其他单元格的文本?

我也试过 cell.stepTextField.removeFromSuperview() 但这将完全删除单元格的文本字段,这不是我想要的。

请注意,我没有在删除函数中对 DataSource 进行任何更新,因为我仅在 Save 函数中获取表视图的所有文本字段的值。

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if tableView == stepTableView {

        if editingStyle == .Delete {
            // Delete the row from the data source
            if stepOrder.count > 1 {

                let cell = self.stepTableView.cellForRowAtIndexPath(indexPath) as! StepCell?
                cell!.stepTextField.text = ""
                stepTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            }

        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }

    }

}

(更新) cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if tableView == self.stepTableView {
        let aCell = tableView.dequeueReusableCellWithIdentifier("StepCell", forIndexPath: indexPath) as! StepCell
        stepTextField = aCell.getTextField()
        aCell.configureStepOrder(stepOrder[indexPath.row])
        aCell.stepTextField.delegate = self
        cell = aCell
    }

}

创建一个数组来存储用户所做的所有更改... 其中索引将是您的手机号码

var textFieldArray = [String]()

现在,当用户点击“添加”步骤时,会在 textFieldArray 中追加一个空字符串

并在 cellForRowAtIndexPath 中添加此

cell.stepTextField.text = textFieldArray[indexPath.row]
cell.stepTextField.tag = indexPath.row

现在,当用户删除单元格时,从 textFieldArray 中删除该元素并重新加载 tableView

textFieldArray.removeAtIndex(indexPath.row)
tableView.reload()

做自己想做的最安全的方法是

  1. 为数据源使用临时数组。在显示 table 视图时创建已保存数组的副本。
  2. 始终将您对 table 视图所做的更改与临时数据源(插入、编辑、删除)同步。您可以在数组中为空单元格设置一个空字符串。
  3. 如果要保存更改,只需将临时数组复制到已保存的数组即可。一个简单的作业就可以了。

至于文本更改,请确保实现所需的委托方法。

希望对您有所帮助!