我有一个TableView,允许用户添加文本输入单元格 .
我实现了textfield委托方法,该方法监视单元格文本字段中的更改并将文本值存储在数组中 .
我目前将 indexPath.row
的cellForRowAtIndexPath方法指定为单元格文本字段的标记值 . 我使用该标记作为更新值的数组索引 .
但是,一旦我删除了一些单元格并添加新单元格来存储新值,这种方法就会引发问题 . 值存储在数组的随机索引中 .
即使在删除某些单元格后,如何以与表格单元格相同的索引顺序保存数组中的值?
var stepCount = 1
var stepOrder = ["1"]
var steps = [""]
@IBAction func stepTextFieldDidChange(sender: UITextField) {
steps[stepTextField.tag] = sender.text!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell?
if tableView == self.stepTableView {
let aCell = tableView.dequeueReusableCellWithIdentifier("StepCell", forIndexPath: indexPath) as! StepCell
stepTextField = aCell.getTextField()
stepTextField.tag = indexPath.row
aCell.stepTextField.delegate = self
aCell.configureStepCell(stepOrder[indexPath.row], step: steps[indexPath.row])
cell = aCell
}
return cell
}
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 {
steps.removeAtIndex(indexPath.row)
stepTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
stepTableView.reloadData()
}
} 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
}
}
}
@IBAction func addStep(sender: AnyObject) {
stepCount++
stepOrder.append("\(stepCount)")
steps.append("")
stepTextField.becomeFirstResponder()
stepTableView.reloadData()
}
1 回答
使用标签很困难,因为正如您所知,索引将随着您操作表数据而改变 .
虽然对于一个简单的字符串来说有点开销,但我会创建一个
Step
类并存储这些类的数组 . 然后,您可以在自定义单元格中存储对Step
实例的引用,并从委托方法更新它 .关于委托的主题,您应该将
UITextField
委托方法移动到您的单元类中,并提供一个新协议,让您的视图控制器知道更改 .在您的视图控制器中,您将拥有: