Best approach for editing text fields in a table view cell

后端 未结 3 1432
暗喜
暗喜 2021-01-03 03:05

In my app I\'ve got a number of views that need to be in-place editable. I\'ve got the tableviewcells setup to include a UITextF

相关标签:
3条回答
  • 2021-01-03 03:24

    The best way is to follow MVC and implement your model, which in your case is the textfield values. What you do is store those values in an array, and in your cellForIndexPath method you reference the correct value in the array. For example, the first row of the table (indexPath.row == 0) would retrieve the first element in the array. Changes in the textField would be recorded on the corresponding element in the array.

    0 讨论(0)
  • 2021-01-03 03:34
    • Subclass UITableViewCell and add a UITextField in it's init method.

    • create a protocol for the custom cell class. when UITextField begin editing or end editing call the delegate's method.

    • in controller, implement the custom cell's protocol and set the indexpath row value to cell's tag in tableView:cellForRowAtIndexPath:

    so every time you edit UITextField, you can know in controller which row is editing (via cell's tag)

    0 讨论(0)
  • 2021-01-03 03:40
    1. Store the values for all of your text fields in a mutable array in your data model.

    2. In tableView:willDisplayCell:forRowAtIndexPath: set your text field's value, using the value from your array based on the index path.

    3. When a text field ends editing, store the value back in the array immediately. There is already a protocol for this (so no need to write your own), but it is a little trickier than normal because you are not handed the indexPath and need to find the one associated with your text field:

      - (void) textFieldDidEndEditing:(UITextField *)textField {
          CGRect location = [self convertRect:textField.frame toView:self.tableView];
          NSIndexPath *indexPath = [[self.tableView indexPathsForRowsInRect:location] objectAtIndex:0];
      
          // Save the contents of the text field into your array:
          [yourArray replaceObjectAtIndex:indexPath.row withObject:textField.text];
      }
      
    0 讨论(0)
提交回复
热议问题