0

我更新了代码

嗨,我在我的 iOS 应用程序中使用从 Web 服务填充的 tableview 实现无限滚动,页码每次跳 4 并且不递增每个页面有 10 个项目从 tableview 放入数组中以显示。

我的代码

@interface TableViewController () 

@end

@implementation TableViewController
@synthesize  articlesArray;
@synthesize currentpage;
@synthesize articles;
@synthesize page;
@synthesize rowww;

- (void)viewDidLoad {
[super viewDidLoad];
self.articlesArray = [[NSMutableArray alloc] init];
self.articles = [[NSMutableArray alloc]init];
currentpage = 1;
page = 2;
[self fetchData:(int)currentpage];
[self.tableView registerNib:[UINib nibWithNibName:@"ArticleCell"   bundle:nil] forCellReuseIdentifier:@"ArticleCell"];
}

-(void)makeRequest:(int)page1{
if ([DGUtilFunctions isInternetAvailable])
{
NSString *urlString = [NSString
                       stringWithFormat:@"http://url/wp-json/wp/v2/posts?page=%d",(int) page1];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
NSData *theData = [NSURLConnection sendSynchronousRequest:request
                                        returningResponse:nil
                                                    error:nil];
self.articles = [NSJSONSerialization JSONObjectWithData:theData
                                                     options:NSJSONReadingMutableContainers
                                                       error:nil];
NSLog(@"self.articles %@",self.articles);
}
else
{
    UIAlertController* _alertView = [ UIAlertController alertControllerWithTitle:nil
                                                                         message:@"Veuillez vous connecter à internet. "                                         preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action){} ];
    [_alertView addAction:defaultAction ];
    [self presentViewController:_alertView animated:YES completion:nil];
}
}

-(void) fetchData:(int)page2 {
if ([DGUtilFunctions isInternetAvailable])
{
   NSString *urlString = [NSString
                           stringWithFormat:@"http://url/wp-json/wp/v2/posts?&page=%d", (int)page2];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    NSData *theData = [NSURLConnection sendSynchronousRequest:request
                                            returningResponse:nil
                                                        error:nil];
    self.articlesArray = [NSJSONSerialization JSONObjectWithData:theData
                                                         options:NSJSONReadingMutableContainers
                                                           error:nil];
    NSLog(@"articlesarray %@",self.articlesArray);
}
else
{
    UIAlertController* _alertView = [ UIAlertController alertControllerWithTitle:nil
                                                                         message:@"Veuillez vous connecter à internet. "                                         preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action){} ];
    [_alertView addAction:defaultAction ];
    [self presentViewController:_alertView animated:YES completion:nil];  
}

}

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;

float reload_distance = 40;
if(y > h + reload_distance) {
    NSLog(@"load more rows");

    [self makeRequest:(int)page];
    page++;
    NSLog(@"currentpage %d",(int)page);
    [self.articlesArray addObjectsFromArray:self.articles];

    [self.tableView reloadData];

}
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0)
{
    return 0;
}
else{
    return [self.articlesArray count] + [self.articlesArray count] / 4;
}

}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(self.sidebarMenuOpen == YES){

    return nil;
} else {

    return indexPath;
}
}

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

NSInteger row = [indexPath row];
if (3 == (row % 4)) {  // or 0 == if you  want the first cell to be an ad!
    static NSString *MyIdentifier = @"AdCell";
    AdViewCell  *cell = (AdViewCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if ((cell == nil) || (![cell isKindOfClass: AdViewCell.class]))
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AdCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell = [[AdViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:MyIdentifier] ;

    }
    GADBannerView *bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeMediumRectangle];
    double width = (cell.contentView.frame.size.width/2)-(bannerView.frame.size.width/2);
    double heigth = (cell.contentView.frame.size.height/2)-(bannerView.frame.size.height/2);
    bannerView =[[GADBannerView alloc] initWithFrame:CGRectMake(width,heigth,300,250)];
    bannerView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin   |
                                   UIViewAutoresizingFlexibleRightMargin  |
                                   UIViewAutoresizingFlexibleTopMargin    |
                                   UIViewAutoresizingFlexibleBottomMargin);

      bannerView.adUnitID = @"";  //admob
    bannerView.rootViewController =self;
    GADRequest *request = [GADRequest request];
    [bannerView loadRequest:request];


    [cell.contentView addSubview:bannerView];

    return cell;
}
else {
    static NSString *simpleTableIdentifier = @"ArticleCell";
    ArticleViewCell *cell = (ArticleViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if ((cell == nil) || (![cell isKindOfClass: ArticleViewCell.class]))
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ArticleCell" owner:self options:nil];
        cell = [nib objectAtIndex:1];
        cell = [[ArticleViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:simpleTableIdentifier] ;
    }
    NSInteger offset = indexPath.row / 4;
    NSInteger roww = indexPath.row - offset;
    rowww = roww;
    NSDictionary * tempDictionary = [self.articlesArray objectAtIndex:roww];
    NSString *imageUrl = [[self.articlesArray objectAtIndex:roww]objectForKey:@"featured_image"];

    imageUrl = [imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl ] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image){
                // Set your image over here
            }else{
                //something went wrong
                NSLog(@"Error occured : %@", [error description]);
            }

        }];
    });

    NSString * title=[tempDictionary valueForKeyPath:@"title"];

    cell.titleLabel.text = title;

    return cell;

}     
}

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {
  [self performSegueWithIdentifier:@"showarticle" sender:self];
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return NO;
}

@end

谢谢

4

2 回答 2

0

想象一个UITableView10 UITableViewCells

一旦UITableView加载,它将调用tableView:willDisplayCell:forRowAtIndexPath每个单元格。每次调用此方法时,您的实现都会增加页码,这会导致页码从 1 跳转到第 10 页。您应该摆脱此方法。

相反,您应该只依赖- (void)scrollViewDidScroll:(UIScrollView *)scrollView回调。尝试这个:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView_
{
CGFloat actualPosition = scrollView_.contentOffset.y;
CGFloat contentHeight = scrollView_.contentSize.height - (self.tableview.frame.size.height);
if (actualPosition >= contentHeight) {
    [self makeRequet:++currentPage];
    [self.articlesArray addObjectsFromArray:self.articlesArray];
    [self.tableView reloadData];
}
于 2016-11-03T11:56:22.030 回答
0

你只需要使用这个

[tableView insertRowsAtIndexPaths:@[indexPathArray]]

在您的请求完成处理程序块中

并且不要忘记增加您的行数

  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
于 2016-11-03T10:28:27.937 回答