我试图从tableViewCells中的UITextField中获取信息。我的viewcontroller是我的每个单元格的委托,每个单元格都是一个文本字段委托。在textfieldDidEndEditing中,我在视图控制器中调用一个委托方法,该方法应该确定它是哪个单元格并将信息存储在单元格的文本字段中。但是,我的indexPathForCell与cellForRowAtIndexPath中的不对应。
这是我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch (indexPath.section, indexPath.row) {
case (0,0):
cell = self.informationCell(withInstructions: "First name", andAnswer: employee.first_name!)
break
case (0,1):
cell = self.informationCell(withInstructions: "Last name", andAnswer: employee.last_name!)
break
case (0,2):
cell = self.informationCell(withInstructions: "Job title", andAnswer: employee.job_title!)
break
case (1,0):
cell = self.informationCell(withInstructions: "Company name", andAnswer: employee.company_name!)
break
case (1,1):
cell = self.informationCell(withInstructions: "Target hours per week", andAnswer: employee.hours_per_week == 0 ? "" : "\(employee.hours_per_week!)")
break
case (1,2):
cell = self.informationCell(withInstructions: "Wage per hour", andAnswer: employee.wage_per_hour! == 0 ? "" : "\(employee.wage_per_hour!)")
break
default: assert(false, "Too many rows?")
return cell!
}
我在哪里检索信息:
func informationTextDidChange(sender: InformationEnterBaseCell) {
let indexPath = self.tableView.indexPathForCell(sender)
print((indexPath!.section, indexPath!.row))
switch (indexPath!.section, indexPath!.row) {
case (0,0):
self.employee.first_name = sender.textfield.text
break
case (0,1):
self.employee.last_name = sender.textfield.text
break
case (0,2):
self.employee.job_title = sender.textfield.text
break
case (1,0):
self.employee.company_name = sender.textfield.text
break
case (1,1):
if let hours = Double(sender.textfield.text!) {
self.employee.hours_per_week = hours
}
break
case (1,2):
if let wage = Double(sender.textfield.text!) {
self.employee.wage_per_hour = wage
}
break
default: assert(false, "Too many rows?")
}
}
我的问题是(section,row)的连音符不再对应。我想知道为什么会这样,以及我如何解决它或更好地解决这个问题。我知道单元格被重用了,但我认为indexPath的行和部分保持不变。感谢您的任何帮助。
编辑:
我在这个函数中设置了委托:
private func informationCell(withInstructions instructions: String, andAnswer answer: String) -> InformationEnterBaseCell {
let cell = InformationEnterBaseCell()
cell.configureWithInstructions(instructions, andAnswer: answer)
cell.delegate = self
return cell
}