Reload UITableView when navigating back?

前端 未结 7 1674
醉梦人生
醉梦人生 2021-01-30 06:38

I have a top level UIViewController that contains a UITableView. The top level UIViewController instantiates a NavigationController

7条回答
  •  无人及你
    2021-01-30 06:56

    If you only want to reload the cell that was selected, override viewWillAppear: in your custom subclass of UITableViewController like so:

    - (void)viewWillAppear:(BOOL)animated
    {
        NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];
        [super viewWillAppear:animated]; // clears selection
        if (selectedRowIndexPath) {
            [self.tableView reloadRowsAtIndexPaths:@[selectedRowIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
    

    NOTE: Assuming you've left clearsSelectionOnViewWillAppear set to YES (the default), you must get the index path of the selected row before calling super, which clears the selection.

    Also, the solution of @ZoranSimic to just call [self.tablView reloadData] is acceptable as it's less code and still efficient.

    Finally, perhaps the best way to keep your table view's cells in sync with the model objects they represent is to do like NSFetchedResultsController and use key-value observing (KVO) and/or NSNotification to inform your table view controller when model objects have changed so that it can reload the corresponding cells. The table view controller could begin observing changes to its model objects in viewDidLoad and end observing in dealloc (and anywhere you manually unload self.view).

提交回复
热议问题