Подтвердить что ты не робот

Как загрузить мое табличное изображение с разбивкой по страницам?

У меня есть табличное представление в моем приложении, в которое я загружаю различные типы ячеек. Это прекрасно и хорошо работает. Но теперь мне нужно сделать разбивку на страницы. Мне нужно передать номер страницы в службу один, два и т.д. И загрузить ее, когда заканчивается первая страница. Для первого я загружаю счет 5, после этого, когда заканчивается прокрутка, мне нужно загрузить следующий. Я новичок в этой разбивке на страницы. Может ли кто-нибудь дать мне направление следовать? Я так пробовал, но он станет бесконечным циклом `

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *) cell     forRowAtIndexPath:(NSIndexPath *)indexPath
{
    int count1 = [array count];
    NSLog(@"%d",count1);
     NSLog(@"%d",indexPath.section);
    NSLog(@"%d",max);
    NSLog(@"%d",min);

    if(indexPath.section == count1 - 1) // If going to display last row available in your source
    {

        NSLog(@"%d",max);
          NSLog(@"%d",min);


        if(min <= max) 
        {



            [self getmessages:min];
        }
        else
        {
            self.mtableview.tableFooterView = nil; //You can add an activity indicator in tableview footer in viewDidLoad to show a loading status to user.
        }

    }
}

`

4b9b3361

Ответ 1

UITableView может поддерживать скимминг во многих рядах данных, однако извлечение большого количества удаленных данных может замедлить ваше приложение, использовать слишком много памяти и болота вашего веб-сервера. Это все расточительно, если пользователи никогда не будут прокручивать их так далеко. В этом эпизоде ​​вы узнаете, как выполнять автоматическую подкачку UITableView с помощью простой техники.

Инициализация

- (void)viewDidLoad {
    [super viewDidLoad];

    self.beers = [NSMutableArray array];
    _currentPage = 0;
}

Выдать запрос HTTP для текущей страницы

- (void)fetchBeers {
    NSString *urlString = [NSString 
      stringWithFormat:@"http://localhost:3000/beers.json?page=%d", 
      _currentPage];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = 
      [[AFJSONRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:
      ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"responseObject %@", responseObject);

        _totalPages = [[responseObject 
          objectForKey:@"total_pages"] intValue];

        for (id beerDictionary in [responseObject 
                                    objectForKey:@"beers"]) {
            Beer *beer = [[Beer alloc] 
              initWithDictionary:beerDictionary];
            if (![self.beers containsObject:beer]) {
                [self.beers addObject:beer];
            }

            [beer release];
        }

        [self.tableView reloadData];

    } failure:
      ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", [error localizedDescription]);
        [[[[UIAlertView alloc] 
          initWithTitle:@"Error fetching beers!"
                message:@"Please try again later"
               delegate:nil
          cancelButtonTitle:@"OK"
          otherButtonTitles:nil] autorelease] show];
    }];

    [operation start];
    [operation release];
}

Смещение числа строк

- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section {
    if (_currentPage == 0) {
        return 1;
    }

    if (_currentPage < _totalPages) {
        return self.beers.count + 1;
    }
    return self.beers.count;
}

Отобразить ячейки

- (UITableViewCell *)beerCellForIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [self.tableView 
dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] 
            initWithStyle:UITableViewCellStyleSubtitle
          reuseIdentifier:cellIdentifier] autorelease];
    }

    Beer *beer = [self.beers objectAtIndex:indexPath.row];
    cell.textLabel.text = beer.name;
    cell.detailTextLabel.text = beer.brewery;

    return cell;
}

- (UITableViewCell *)loadingCell {
    UITableViewCell *cell = [[[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleDefault
               reuseIdentifier:nil] autorelease];

    UIActivityIndicatorView *activityIndicator = 
      [[UIActivityIndicatorView alloc] 
      initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.center = cell.center;
    [cell addSubview:activityIndicator];
    [activityIndicator release];

    [activityIndicator startAnimating];

    cell.tag = kLoadingCellTag;

    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.beers.count) {
        return [self beerCellForIndexPath:indexPath];
    } else {
        return [self loadingCell];
    }
}

Получение следующей страницы

- (void)tableView:(UITableView *)tableView 
  willDisplayCell:(UITableViewCell *)cell 
forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (cell.tag == kLoadingCellTag) {
        _currentPage++;
        [self fetchBeers];
    }
}

Этот пример из NSScreencast Episode 8 - Automatic UITableViewPaging.

Ответ 2

Из кода, который вы опубликовали: вы уверены, что требуется indexPath.section. Если вы используете раздел, то убедитесь, что метод - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView должен возвращать счет вашего источника данных, а не - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section.

Если проблема по-прежнему сохраняется, отправьте приведенный выше код методов.