2016-11-03 3 views
0

Я обновил кодTableview прыжок ИОС бесконечный свиток индекс страницы

привет Я использую TableView населенную из веб-службы в моем IOS приложение реализующий бесконечный свиток номер страницы перескакивает на 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 

благодарит

+0

'-makeRequest:' является синхронным или асинхронным? – Larme

+0

NSData * theData = [NSURLConnection sendSynchronousRequest: request returnResponse: nil error: nil]; – sinfils

+0

Покажите свой код для метода _makeRequest: _. – Adeel

ответ

0

Вам просто нужно использовать этот

[tableView insertRowsAtIndexPaths:@[indexPathArray]]

в вашем запроса блока обработчика завершения

и не забудьте увеличить количество строк в

  • (NSInteger) Tableview: (UITableView *) Tableview numberOfRowsInSection: раздел (NSInteger)
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]; 
} 
+0

, что делает цикл циклов бесконечным. – sinfils

+0

Сначала удалите таблицу '- (void) tableView: (UITableView *) tableView willDisplayCell: (UITableViewCell *) для метода forRowAtIndexPath: (NSIndexPath *) indexPath', а затем используйте' - (void) scrollViewDidScroll: (UIScrollView *) scrollView'. –

+0

Если это все еще не работает, попробуйте переопределить '- (void) scrollViewDidEndDecelerating: (UIScrollView *) scrollView' вместо' - (void) scrollViewDidScroll: (UIScrollView *) scrollView'. –

Смежные вопросы