Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload a UITable on the fly when editing a UITextField inside one of the cells

I have a UITable containing some customs UITableCells. Those cells contain a few UILabels and a UITextField. The datasource of the table comes from a main controller's property. (This controller is also the delegate and the dataSource for the table).

Here's a simplified screenshot of the UI:

schreenshot

Now, I need to update "on the fly" the content of all the UILabels when the user edits one of the UITextFields. To do so, at the I am listening to the "Editing Changed" event at the UITextField level. This triggers the following action:

- (IBAction) editChangeHandler: (id) sender {
    MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [[delegate.viewController.myDataSourceArray objectAtIndex:self.rowIndex] setANumber: [theTextField.text intValue]];
    [delegate.viewController reloadRows];
}

The reloadRows method in the viewController is as such:

- (void) reloadRows {
    NSLog(@"called reloadRows");
    //perform some calculations on the data source objects here...
    [theUITable reloadData];
}

My problem here is that whenever the user changes the value in the field, the reloadRows method is successfully called, so is apparently the reloadData but it also causes the keyboard to be dismissed.

So in the end, the user can only touch one key when editing the TextField before the keyboard is dismissed and the table reloaded.

Does anybody knows a solution to this or have experienced the same issue?

like image 439
Saze Avatar asked Nov 21 '11 22:11

Saze


2 Answers

You can selectively modify rows as needed, rather than updating the whole table (doing this is updating the cell you are currently working in, resetting its state).

Look at:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

Additionally, you can edit those cells directly by obtaining the cell via:

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath

if you don't want to have to rebuild those cells.

like image 172
MarkPowell Avatar answered Nov 05 '22 00:11

MarkPowell


I ran into the same problem. In my case I was trying to create a generic controller, so writing a specific method to manually rebuild the cells wasn't a good option.

Here is the solution I came up with:

  1. Temporarily make a text field in some other cell in the table become the first responder.
  2. Call reloadRowsAtIndexPaths to reload the cell your user was editing.
  3. Make the field the user was editing become first responder again.

It works like a charm. The keyboard stays visible with no flashing at all, the cell gets properly refreshed, and the user can continue typing in the same field they were originally editing.

like image 25
Alan Keele Avatar answered Nov 05 '22 01:11

Alan Keele