1
votes

I have a UITableView with several cells. Each cell has a label and a UITextField. When I load the ViewController, the UITextFields have the initial value, and the user can edit those values. Now I want to add a save button to save the changes, but I have problem getting the values in the UITextFields after editing. I think I need to use tags for the textfields, but I don't know how. Here is my code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:EditProfileCell = tableView.dequeueReusableCellWithIdentifier("profile") as! EditProfileCell
    if (indexPath.row == 1){
    cell.setRow("label", value: "initial value")
    cell.itemValue.tag = indexPath.row
}

@IBAction func saveTapped(sender: UIButton) {
    print(self.tableView(profileTableView, cellForRowAtIndexPath: NSIndexPath(forRow: 1, inSection: 1)).viewWithTag(1))
}

When save button is tapped, it prints the initial value instead of the value after editing. I need help with get the value after editing.

EDIT1:

I found that I can get the edited value in the didSelectRowAtIndexPath function. But the problem is when I click on the textfield(the textfield enters editing mode), the didSelectRowAtIndexPath is not called until I tap the space within the cell but outside the textfield. So my problem becomes how to trigger didSelectRowAtIndexPath when I only click on the textfield.

1
An understanding of classes and is-a vs has-a should help you a lot with this. - Stephen J

1 Answers

0
votes

The problem is that when you call saveTapped inside you are calling cellForRowAtIndexPath and in there you have:

cell.setRow("label", value: "initial value")

Basically that's why you are getting the initial value. The other problem is that cells on table view are reused. That is you can have 1000000 records but table view will create only ~9-12 cells and will use them to display information for any of those 1000000 rows.

What you need to do is have a model. Some kind of object where you can store and retrieve those values for the cell. A natural choice is an Array in your case Array containing Strings. Pleas check this tutorial and take a special notice how NSArray *tableData; is used in there.

Good luck! :D