Динамический NumberOfRowsInSection - PullRequest
       3

Динамический NumberOfRowsInSection

0 голосов
/ 11 февраля 2012

У меня есть приложение для iphone, которое считывает поле «категория» из XML-файла, который является RSS-фидом.Мое приложение работает так, что оно отображает содержимое RSS-канала в табличном представлении по категориям из поля xml "category".

Я немного новичок в представлениях таблиц, поэтому я немного потерян.

У меня просто есть две категории в XML-файле, одна называется "Без категории", а другая - "Promos".

Текущий код:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:         
            return itemsToDisplay.count;
        default:   
            return itemsToDisplay.count;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if(section == 0)
        return @"Promoções";
    else
        return @"Não Categorizados";
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 0) {
        MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
        if([item.category isEqualToString:@"PROMOS"]){
            MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
            NSLog(@"ENTRA NO PROMOS____________________");
            NSLog(@"item.category = %@-------------->", item.category);
            // Process
            NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : @"[No Title]";
            NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : @"[No Summary]";
            NSLog(@"IMAGE (table View) = %@",item.image);

            NSURL *url = [NSURL URLWithString:item.image];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
            [request startAsynchronous];
            NSData * imageData = [NSData dataWithContentsOfURL:url];
            UIImage * image = [UIImage imageWithData:imageData];
            // Set
            cell.imageView.image = image;
            cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
            cell.textLabel.text = itemTitle;
            NSMutableString *subtitle = [NSMutableString string];
            if (item.date) [subtitle appendFormat:@"%@: ", [formatter stringFromDate:item.date]];
            [subtitle appendString:itemSummary];
            cell.detailTextLabel.text = subtitle;
            NSLog(@"FIM DO PROMOS_____________________");
        }
    }else if(indexPath.section == 1){
        MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
        if([item.category isEqualToString:@"Uncategorized"]){
            NSLog(@"ENTRA NO UNCATEGORIZED__________");
            NSLog(@"item.category = %@------------------>", item.category);
            // Process
            NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : @"[No Title]";
            NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : @"[No Summary]";
            NSLog(@"IMAGE (table View) = %@",item.image);

            NSURL *url = [NSURL URLWithString:item.image];
            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
            [request startAsynchronous];
            NSData * imageData = [NSData dataWithContentsOfURL:url];
            UIImage * image = [UIImage imageWithData:imageData];
            // Set
            cell.imageView.image = image;
            cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
            cell.textLabel.text = itemTitle;
            NSMutableString *subtitle = [NSMutableString string];
            if (item.date) [subtitle appendFormat:@"%@: ", [formatter stringFromDate:item.date]];
            [subtitle appendString:itemSummary];
            cell.detailTextLabel.text = subtitle;
            NSLog(@"FIM DO UNCATEGORIZED________________");
        }
    }
   return cell;
}

У меня проблема в том, чточто он отображает одинаковое количество ячеек для обеих категорий и не фильтрует их по категориям.

С наилучшими пожеланиями.

Ответы [ 3 ]

2 голосов
/ 11 февраля 2012

конечно, это так.Посмотрите на ваш код (и комментарии, которые я добавил):

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:         
            return itemsToDisplay.count;   // <- this
        default:   
            return itemsToDisplay.count;   // is exactly the same line of code as this one
    }
}

поместите Uncategorized и Promos в разные NSArrays.

NSArray *promos;             // add all promos to this array
NSArray *uncategorized;      // and eerything else into this array


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:         
            return [promos count];          // return the number of promos
        default:   
            return [uncategorized count];   // return the number of uncategorized objects
    }
    return 0;
}
1 голос
/ 11 февраля 2012

потому что вы возвращаете одинаковое количество элементов для разделов 0 и 1: return itemsToDisplay.count

Кроме того, вы также используете один и тот же элемент данных для ячеек сечения 0 и 1: MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];

У вас должно быть 2 отдельных массива элементов, например, itemsUncategorized и itemsPromos, и убедитесь, что они хранят разные элементы данных для ваших списков "Без категории" и "Промо".

Или вы можете установить флажок внутри MWFeedItem, указав, является ли он элементом без категории или элементом Promos. Это немного сложнее, но возможен другой подход.

Пример:

typedef enum {
   ITEM_UNCATEGORIZED,
   ITEM_PROMOS,
} ITEM_TYPE;

@interface MWFeedItem {
@private
   NSString * title;
   NSString * summary;
   UIImage * image;
   ITEM_TYPE itemType;
}

// TODO: put your properties here for the ivars of this class...
// TODO: put your item methods here, if any...
@end
1 голос
/ 11 февраля 2012
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category = %@", @"PROMOS"];

NSArray *promosArray = [itemsToDisplay filteredArrayUsingPredicate:predicate];

switch (section) { 

    case 0:

        return [promosArray count];
    default:

        return [itemsToDisplay count] - [promosArray count];
}

Для генерации клеток вы должны использовать этот способ тоже. Или вы можете предварительно фильтровать данные (для ускорения)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...