【问题标题】:How to add pagination in UITableView.? [closed]如何在 UITableView 中添加分页。? [关闭]
【发布时间】:2023-04-07 08:49:01
【问题描述】:

我从 API 解析第一页的数据并将其添加到 UITableView,现在页面可以是多个,比如说 100,我也从 API 获得总页数。但是我将如何在 tableView 中为每个页面实现它并在滚动时显示指示器。看看我的代码

NSURL *theURL = [NSURL URLWithString:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:1"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

//Specify method of request(Get or Post)
[theRequest setHTTPMethod:@"GET"];

//Pass some default parameter(like content-type etc.)
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

[theRequest addValue:token forHTTPHeaderField:@"x-access-token"];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;

NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
if (responseData == nil)
{
    return;
}

NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&theError];
NSLog(@"url to send request= %@",theURL);
NSLog(@"%@",dataDictionaryResponse);



NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  NSLog(@"Response:%@ %@\n", response, error);
                                  if(error == nil)
                                  {

                                      NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                      NSLog(@"Data = %@",text);
                                  }

                                  dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];

                                  NSArray *total =  [dictionary objectForKey:@"total"];
                                  NSLog(@"latlop %@", total);




                                  NSArray *IDArray = [dictionary objectForKey:@"docs"];
                                  for (NSDictionary *Dict in IDArray)
                                  {

                                      NSMutableDictionary *temp = [NSMutableDictionary new];
                                      [temp setObject:[Dict objectForKey:@"_id"] forKey:@"_id"];

                                      NSLog(@"temp %@", temp );

                                      NSString *booknumber = [Dict objectForKey:@"bookingNumber"];
                                      if([booknumber length] != 0)
                                          [temp setObject:booknumber forKey:@"bookingNumber"];

                                      NSMutableDictionary *stp1 = [Dict objectForKey:@"stop1"];

                                      if ([[stp1 allKeys] containsObject:@"address"]) {

                                          [temp setObject:[stp1 objectForKey:@"address"] forKey:@"address"];




                                          ];

                                      }

                                      NSMutableDictionary *stp2 = [Dict objectForKey:@"stop2"];

                                      if ([[stp2 allKeys] containsObject:@"address"]) {

                                          [temp setObject:[stp2 objectForKey:@"address"] forKey:@"address1"];


                                          NSArray *latlongstp2 =  [stp2 objectForKey:@"location"];
                                          [temp setObject:[latlongstp2 objectAtIndex:0] forKey:@"latitude"];
                                          [temp setObject:[latlongstp2 objectAtIndex:1] forKey:@"longitude"];

                                      }



                                      NSMutableDictionary *currentloc = [Dict objectForKey:@"currentLocation"];

                                      if ([[currentloc allKeys] containsObject:@"address"]) {

                                          [temp setObject:[currentloc objectForKey:@"address"] forKey:@"address1"];


                                      }


                                      [getid addObject:temp];

                                  }


                                  if (getid.count>0)
                                  {
                                      [self updateTable];
                                  }



                              }];

[task resume];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;    //count of section
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return [getid count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [getid count] - 1 ) {

    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ScheduleTableViewCell *cell   = [tableView      dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    cell.BookingId.text  = [[getid        objectAtIndex:indexPath.row]objectForKey:@"_id"];
    cell.BookingNo.text  = [[getid objectAtIndex:indexPath.row]objectForKey:@"bookingNumber"];
    cell.stop1.text  = [[getid objectAtIndex:indexPath.row]objectForKey:@"address"];
    cell.stop2.text = [[getid objectAtIndex:indexPath.row] objectForKey:@"address1"];
    cell.Currentloc.text = [[getid objectAtIndex:indexPath.row]  objectForKey:@"address"];


    return cell;
}

【问题讨论】:

  • 互联网上有许多用于实现分页的技术以及很好的示例。尝试这些并修改它们以满足您的需要。这是一个很好的例子 - iosnomad.com/blog/2014/4/21/fluent-pagination
  • @TheRohanSanap 先生,我不想使用第三方库
  • 我不认为我指定的示例链接使用任何第三方库进行分页。他们只是用例子解释了逻辑。无论如何,这是另一个 - grokswift.com/rest-tableview-in-swift

标签: ios objective-c json


【解决方案1】:

有很多方法可以实现这一点,如下所示:

  • 首先,您需要创建一个全局NSMutableArray,它会加载到TableView Delegates 和DataSaurce
  • 现在在您的 api 调用中,您需要在全局数组中添加该记录。
  • 在最后一个单元格或tableview 上,您可以根据您的 API 使用下一页 URL 再次调用它,并在每次调用时重新加载表
  • 您可以使用 github 上提供的更多第三方库进行加载:

https://github.com/OpenFibers/DragRefreshAndLoadMoreTableDemo

https://github.com/Abizern/PartialTable

https://github.com/robertmryan/UITableView-Bottom-Refresh

根据您的代码:

在 .h 类中

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
   NSURL* nextURL;
    int currentPage;

}

.M 类

- (void)viewDidLoad {

    currentPage = 1;

    [self LoadData];
    [super viewDidLoad];

}


-(void)LoadData
{

    NSURL *theURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:%d",currentPage]];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

    //Specify method of request(Get or Post)
    [theRequest setHTTPMethod:@"GET"];

    //Pass some default parameter(like content-type etc.)
    [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

    [theRequest addValue:token forHTTPHeaderField:@"x-access-token"];
    NSURLResponse *theResponse = NULL;
    NSError *theError = NULL;

    NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
    if (responseData == nil)
    {
        return;
    }

    NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&theError];
    NSLog(@"url to send request= %@",theURL);
    NSLog(@"%@",dataDictionaryResponse);



    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {

                                      NSLog(@"Response:%@ %@\n", response, error);
                                      if(error == nil)
                                      {

                                          NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                          NSLog(@"Data = %@",text);
                                      }


                                      currentPage ++;
                                      dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:@"data"];

                                      NSArray *total =  [dictionary objectForKey:@"total"];
                                      NSLog(@"latlop %@", total);


                                      [getid addObjectsFromArray:total];

                                       [self updateTable];

                                  }];

    [task resume];
}

【讨论】:

  • 为什么你在收到回复时写了太多代码。一旦您得到响应,您只需将其添加到您的主阵列并重新加载它。根据您的主数组在 CellForRowIndex 中编写代码。
  • 好的,先生,我试着处理它
  • 先生,我将如何通过 cellfroindexpath 方法在 url 中添加下一页
  • 创建一个分配 nexturl 的变量。意味着一旦您在成功时调用,您将使用新页码创建下一个 url 并将其分配给下一次调用字符串
  • 先生,如果可能的话,请您在我的代码中编辑一些提示
【解决方案2】:

声明一个全局变量pagingCount,并在viewdidload中初始化为1。

在您的数据获取器方法中进行此更改。

NSURL *theURL = [NSURL URLWithString:@"http://qa.networc.in:1336/api/dispatcher/rideScheduled/:%d",pagingCount];

现在您将传递此分页计数并在最后一个单元格即将显示时调用您的数据获取器方法。 用 +1 更新分页计数

- (void)tableView:(UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == [getid count] - 1 ) {
//call your method of fetching data with paging which will be increased with 1
//increase the pagingCount
pagingCount += 1;

//call your data fetcher
            }
         }

【讨论】:

    【解决方案3】:

    我用下面的代码做了同样的事情

    #pragma mark --- UIScrollView Delegate Method ---
    
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
        float offset = (scrollView.contentOffset.y - (scrollView.contentSize.height - scrollView.frame.size.height));
        btnloadMore.hidden = YES;
    
        if (offset >= 0 && offset <= 105)
        {
            if(isLoadMoreCheck == TRUE)
            {
                NSLog(@"Hi");
                //btnloadMore.hidden = NO;
                [self addMoreData];
            }
        }
    
        NSLog(@"Scroll : %f",offset);
    }
    
    - (void)addMoreData
    {
        isLoadMoreCheck = FALSE;
        isLoadMore = TRUE;
        currentPage++;
        [self getNewsFeeds:currentPage];// Here you can call your method for load next page data
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 2012-03-25
      • 2015-12-09
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多