Search code examples
iosuitableviewsections

How to display section header\Tile after sorting uitableview


I am sorting my tableview by Distributor using the code below (it was Alphabetical by product)

    NSSortDescriptor *aSort =[[NSSortDescriptor alloc] initWithKey:@"Dis" ascending:YES];
    [distribArray sortUsingDescriptors:[NSMutableArray arrayWithObject:aSort]];

    NSLog( @"data from table %@", distribArray);

    [self.tableView reloadData];


    NSLog(@"ok2222222222");
    [[NSUserDefaults standardUserDefaults] setValue:@"Dis" forKey:@"ListBy"];
    [[NSUserDefaults standardUserDefaults] synchronize];

I would like to know what the easiest way to display the Distributor name as a Title header above all the products for that Distributor. I currently display the Distributor name in the DetailsView of the cell for each product.

I would like to go from.

Product 1
Acme
Product 2
Acme
Product 3
Acme

To this below and keep my UITableView\Cells

Acme
Product 1
Product 2
Product 3

.... Many Thanks for any help.


Solution

  • maybe it is not the fastest way, but i think it is simple

    first create a small inner class like this:

    @interface ProductSection
    @property (strong, nonatomic) NSString* sectionName;
    @property (strong, nonatomic) NSMutableArray* products;
    @end
    

    then use this instead your sort:

    NSSortDescriptor *aSort =[[NSSortDescriptor alloc] initWithKey:@"Dis" ascending:YES];
    NSArray* products = [distribArray sortUsingDescriptors:[NSMutableArray arrayWithObject:aSort]];
    
    self.sections = [NSMutableArray array];
    
    NSString* currentDistributor = nil;
    for (Product* p in products) {
        if (![p.Dis isEqualToString:currentDistributor]) {
            ProductSection* section = [[ProductSection alloc] init];
            section.sectionName = p.Dis;
            section.products = [NSMutableArray array];
            [self.sections addObject:section];
    
            currentDistributor = p.Dis;
        }
        ProductSection* section = [self.sections lastObject];
        [section.products addObject:p];
    
    }
    [self.tableView reloadData];
    

    where self.sections is a mutable array of ProductSection

    next use this in your Table View Data Source:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[self.sections objectAtIndex:section] products] count];
    

    }

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sections count];
    

    }

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    [[self.sections objectAtIndex:section] sectionName];
    

    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Product* p = [[[self.sections objectAtIndex:indexPath.section] products] objectAtIndex:indexPath.row];
    ...
    

    }

    hope that will help