What's the best way to refresh a UITableView w

2019-04-10 17:41发布

问题:

I'm pretty new to iPhone development and have struggled to find what I consider to be a neat way around this problem.

I have a user interface where a summary of record data is displayed in a table inside a navigation controller. When the user clicks the accessory button for a row, a new view is pushed onto the navigation controller revealing a view where the user can edit the data in the corresponding record. Once done, the editing view is popped from the navigation controller's stack and the user is returned to the table view.

My problem is that when the user returns to the table view, the table still shows the state of the data before the record was edited. I must therefore reload the table data to show the changes.

It doesn't seem possible to reload the table data before it is displayed as the call only updates displayed records. Reloading it after the table has been displayed results in the old data changing before the user's eyes, which I'm not too happy with.

This seems to me like a pretty normal thing to want to do in an iPhone app.

Can anyone please suggest the best practice approach to doing this? I feel like I'm missing something.

Cheers - Steve.

回答1:

I'd implement this in the following way:

  1. Save indexPath of a clicked cell.

  2. Implement -[UIViewController viewWillAppear:] method of the view controller, which contains the UITableView. If saved indexPath is not nil, reload specified cells with:

    -[UITableView reloadRowsAtIndexPaths:withRowAnimation:]



回答2:

The standard approach may sound like a lot of hassle at first, but is a useful pattern for a lot of situations.

In your tableview class create a method like:

-(void)editDone {
    [self.tableView reloadData];
}

Add a property to your edit controller like:

@property (assign) id delegate;

Set the delegate when your accessory is clicked:

editController.delegate = self;

And when editing is complete, call your method like so:

[delegate performSelector:@selector(editDone) withObject:nil];

You can create similar methods to handle cancel of your edit component, or to carry out dismissing of modal edit controllers, etc. It's considered more classy to put all this in a protocol, if you like.