简体   繁体   English

UItableView在滚动时加载数据

[英]UItableView load data on scroll

In my app I am getting the data from the web-service and I have to display it in UITableView. 在我的应用程序中,我从Web服务获取数据,我必须在UITableView中显示它。 But the condition here is I have to display only 10 records initially,then once the user scroll down I have to load more records.I tried searching it but didn't get any useful answer. 但这里的条件是我最初只需显示10条记录,然后一旦用户向下滚动我必须加载更多记录。我尝试搜索它但没有得到任何有用的答案。 I agree that I will use - 我同意我会用 -

(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

to display the value,but how will I fetch only 10 records from the service and then other record based on scroll. 显示值,但我如何从服务中获取10条记录,然后根据滚动获取其他记录。 Please provide some pointers or sample code. 请提供一些指示或示例代码。

Thanks 谢谢

In case if some one need it,i was able to solve my problem this way. 如果有人需要它,我能够以这种方式解决我的问题。 First thing is you need the server configuration in such a way so that it should return 10 data at a time based on the row which is visible in TableView. 首先,您需要以这种方式配置服务器,以便它应该根据TableView中可见的行一次返回10个数据。 This is the tableView delegate which get called and returns the visible cells in tableView 这是被调用的tableView委托,并返回tableView中的可见单元格

 -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        int lastRow=[nameArray count]-1;
        if(([indexPath row] == lastRow)&&(lastRow<[categoryArray count]))  
        {

            if(tableView==m_pDetailsTableView)    {
                savedScrollPosition=lastRow;
                startCellValue=[NSString stringWithFormat:@"%d",0];
                endCellValue=[NSString stringWithFormat:@"%d",[nameArray count]+10];
                [self connectToServer]; //Method to request to server to get more data
            }
        }
    }

savedscrollPosition variable stores the variable as a point where you want to scroll the table view after load of data. savedscrollPosition变量将变量存储为要在加载数据后滚动表视图的点。

You should read about lazy loading. 你应该阅读延迟加载。 The code is available at Apple's website. 该代码可在Apple的网站上找到。 Download it here 在这里下载

http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html

check the code of 检查代码

- (void)loadImagesForOnscreenRows 

method. 方法。

It uses the same approach you need. 它使用您需要的相同方法。 It gets the current scroll position of the table view and on the basis of that, it will get the cells displayed on the screen and their indexPath. 它获取表视图的当前滚动位置,并在此基础上,它将获取屏幕上显示的单元格及其indexPath。 On the basis of that you will be able to show those cells which are shown in the screen. 在此基础上,您将能够显示屏幕中显示的那些单元格。

For showing 10 rows, a simple calculation is required. 要显示10行,需要进行简单的计算。

Just insert the new data into your datasource see below 只需将新数据插入数据源,如下所示

If you're using xml - check out XMLReader - turn XML into an NSDictionary this sample code below uses AFNetworking (which is non blocking) https://github.com/AFNetworking/AFNetworking/ 如果你正在使用xml - 请查看XMLReader - 将XML转换为NSDictionary,下面的示例代码使用AFNetworking(非阻塞) https://github.com/AFNetworking/AFNetworking/

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        [self fetchMoreData];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self fetchMoreData];
}


- (void)fetchMoreData
{

    if ([resultArray count] > 0)
    {
       NSArray *visiblePaths = [myTableView indexPathsForVisibleRows];
       NSIndexPath *lastRow = [visiblePaths lastObject];

        // Check whether or not the very last row is visible.
        NSInteger numberOfSections = [myTableView numberOfSections];
        NSInteger lastRowSection = [lastRow section];
        NSInteger lastRowRow = [lastRow row];
        NSInteger numberOfRowsInSection = [myTableView numberOfRowsInSection:lastRowSection];

        if (lastRowSection == numberOfSections - 1 &&  
            lastRowRow== numberOfRowsInSection - 1) {

            DLog(@"it's the last row");
            if ([resultArray count]%10 == 0) { // use a divider based on your pagination
               [self fetchNextPage];
            }

        }
    }
}


-(void)getFeeds{
    ENTER_METHOD;

    [resultArray removeAllObjects];
    //reset this
   NSString *url = [NSString stringWithFormat:@"/webserviceurl.xml?offset=0"];
    [httpClient getPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [self parseFeedsXMLString:operation.responseString];
        //  offset = offset + 10; // ONLY if there's results increment

    } failure:^(AFHTTPRequestOperation *operation, id responseObject){
        NSString *detailError=nil;
     }];

}

-(void)fetchNextPage{

    NSString *url = [NSString stringWithFormat:@"/webserviceurl.xml?offset=%d",offset];
    [httpClient getPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {


        DLog(@"operation.responseString:%@",operation.responseString);
        [self parseNextFeedsXMLString:operation.responseString];
       // offset = offset + 10; // ONLY increment if there's results 


    } failure:^(AFHTTPRequestOperation *operation, id responseObject){

    }];

}



- (void)parseFeedsXMLString:(NSString *)xmlString
{

    NSError *parseError = nil;
    NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:xmlString error:&parseError];
    DLog(@"xmlDictionary:%@",xmlDictionary);
    resultArray = [[NSMutableArray arrayWithArray:[[xmlDictionary objectForKey:@"feed"] objectForKey:@"entry"]]retain];

    [myTableView reloadData];
}

-(void)parseNextFeedsXMLString:(NSString *)xmlString
{

    NSError *parseError = nil;
    NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:xmlString error:&parseError];
    DLog(@"xmlDictionary:%@",xmlDictionary);
    //[resultArray insertObject:e atIndex:[resultArray count]];

    NSMutableArray *results  = [NSMutableArray arrayWithArray:[[xmlDictionary objectForKey:@"feed"] objectForKey:@"entry"]];

    if ([results count]) {
        page++;
        for (NSDictionary  *dict in results) {
            [resultArray insertObject:dict atIndex:[results count]];
        }

    }
    [myTableView reloadData];
}

If I correctly understand your question ,you can do the following. 如果我正确理解您的问题,您可以执行以下操作。

1 ) implement scrollViewDidScroll 1)实现scrollViewDidScroll

2 ) check for visible rows in that 2)检查其中的可见行

3 ) if you found the last row just call the web service for loading more data 3)如果您发现最后一行只是调用Web服务来加载更多数据

4 ) on getting the data just reload the table 4)获取数据只需重新加载表

Try it . 试试吧 。

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
    i = i +10;
    NSString *unescaped = mySearchBar.text;
    NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
    [PServiceAPI searchKeyWord:escapedString withOffSet:i Handler:^(NSArray *results, NSError *error) {
        if (error == nil) {
            [arBase addObjectsFromArray:results];
            [myTableView2 reloadData];

        }
    }];

  }
}

You can adjust the return value of tableView:numberOfRowsInSection: method, every time you want to insert ten rows, you can plus 10 to the return value. 你可以调整tableView:numberOfRowsInSection:的返回值tableView:numberOfRowsInSection:方法,每次要插入十行时,都可以加10到返回值。

sorry for my poor english. 抱歉我的英语不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM