Triz
Triz

Reputation: 767

How to put cells into certain sections in a grouped table?

I've got a class of object with a category property (task.category), which is set to an integer value (1, 2, or 3). I'd like to have a grouped table build itself by putting each task into the right section...

How do I get certain cell objects to be drawn in certain sections of a grouped table, based on one of their properties?

Thanks! :)

Upvotes: 0

Views: 613

Answers (1)

Daniel Rinser
Daniel Rinser

Reputation: 8855

There is no way to do that automagically. You still have to implement all necessary methods of UITableViewDataSource. In order for your datasource methods to provide correct data, you should build some suitable data structure first by grouping your tasks by category. The easiest way would be to build a NSDictionary with the category (wrapped in NSNumber) as key and an NSArray of corresponding tasks as value.

To build this dictionary, do something like this (not tested):

NSArray* keys = [NSArray arrayWithObjects:[NSNumber numberWithInteger:1], [NSNumber numberWithInteger:2], [NSNumber numberWithInteger:3], nil];
NSArray* objects = [NSArray arrayWithObjects:[NSMutableArray array], [NSMutableArray array], [NSMutableArray array], nil];
self.dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

for(Task* task in tasks) {    // if tasks is your array holding all tasks
    NSNumber* bucket = [NSNumber numberWithInteger:task.category];
    [[dict objectForKey:bucket] addObject:task];
}

The reason why we have to do this NSNumber boilerplate, is that you can't use primitive values (eg. integers) as dictionary keys.

Once you have this dictionary (self.dict in the code below), just implement the necessary UITableViewDataSource methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;    // supposing you have 3 categories
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray* tasks = [self.dict objectForKey:[NSNumber numberWithInteger:(section + 1)]];
    return [tasks count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray* tasks = [self.dict objectForKey:[NSNumber numberWithInteger:(indexPath.section + 1)]];
    Task* task = [tasks objectAtIndex:indexPath.row];

    // other stuff usually done here (create cell, set content of cell etc.)
}

Of course, this is just one possible approach, but I hope it helps to get you on the right track.

Upvotes: 2

Related Questions