tableview无限滚动索引页跳转ios

时间:2016-11-03 10:19:26

标签: ios objective-c uitableview endlessscroll

我更新了代码

嗨我正在使用从我的iOS应用中的网络服务填充的tableview 实现无限滚动页面编号每次跳过4并且不会增加每页有10个项目从表格视图放入数组中显示。

我的代码

@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

谢谢

2 个答案:

答案 0 :(得分:0)

你只需要使用这个

[tableView insertRowsAtIndexPaths:@[indexPathArray]]

请求完成处理程序块

中的

并且不要忘记增加

中的行数
  • (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

答案 1 :(得分:0)

想象一下UITableView有10 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];
}