infinite UITableView asking for more data from the network as it needs to display more cells

StackOverflow https://stackoverflow.com/questions/21864983

Domanda

Is it possible to 'append' more data to the datasource when a UITableView scrolls and asks for new cells? Similarly like Google image search shows 'infinitly' more images?

I could ask the controller to fetch more data from the network possibly through cellForRowAtIndexPath I figured.. But since tableView:numberOfRowsInSection: is essentialy a fixed number when the table loads or reloads it sounds like a catch22, the tableview wants to know how many rows it should have and you give it more and more. What is the approach and isn't this asking too much from the UITableView design?

This is a test from a future employer btw...

È stato utile?

Soluzione 2

tableView:numberOfRowsInSection: does not have to a fixed number. You can do something like this:

NSMutableArray *data

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [data count];
}

So when you have new items to be displayed, first add it your data array and then call [tableView reloadData]. You could get the data asynchronously but when adding it to your array and reloading the tableview, I would suggest doing it on the main thread or you might observe some strange behaviour. For infinite display of data I use this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    //Your cell code


    if (indexPath.row>[data count]-5) {
        [self getNewData];
    }
}

Your get new data function will be called when you are near the end of your tableview. There you can append your array in any way you want. Also make sure to handle it so that the function isn't called multiple times in one go.

Altri suggerimenti

You should call reloadData (it is smart enough to re-query only visible cells) or reloadSections:withRowAnimation or more complex beginUpdates/insertRowsAtIndexPaths:withRowAnimation:/endUpdates to make UITableView update rows.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top