Apple developer Apple developer - 9 days ago 6
iOS Question

Dynamic sections and rows UITableView

I am new to iOS,

I am developing

UITableView
with Dynamic rows and sections

I want to display all "today" data in first section, "tomorrow" in other section and "Sunday" in other section and so on...

Code I have tried is,

Here is my Array:

{
"callbackSlotId": "1234-1234-3214-1233",
"callbackSlotName": "10:00-10:30",
"day": "today",
"availablenow": true
},
{
"callbackSlotId": "1234-1234-3214-1234",
"callbackSlotName": "11:00-11:30",
"day": "today",
"availablenow": false
},
{
"callbackSlotId": "1234-1234-3214-1235",
"callbackSlotName": "10:30-11:00",
"day": "today",
"availablenow": false
},
{
"callbackSlotId": "1234-1234-3214-1236",
"callbackSlotName": "10:30-11:00",
"day": "tomorrow",
"availablenow": false
},
{
"callbackSlotId": "1234-1234-3214-1237",
"callbackSlotName": "10:30-11:00",
"day": "tomorrow",
"availablenow": false
},
{
"callbackSlotId": "1234-1234-3214-1241",
"callbackSlotName": "10:30-11:00",
"day": "Sunday",
"availablenow": false
}
...
...
...


Using this code it displays all data in multiple sections:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [Array count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [Array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

cell.textLabel.text=[Array objectAtIndex:indexPath.row];

return cell;

}


Can any one help me?
Thanks for reading

Answer

Not tested but you can use idea of my code for separating your array

NSMutableArray *sections = [[NSMutableArray alloc] init];
NSMutableArray *elementsInSection = [[NSMutableArray alloc] init];
for (NSDictionary *dict in Array) {
    NSString *day = [dict objectForKey:@"day"];
    if (![sections containsObject:day]) {
        [sections addObject:day];
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        [arr addObject:dict];
        [elementsInSection addObject:arr];
    } else {
        NSMutableArray *arr = [elementsInSection objectAtIndex:[sections indexOfObject:day]];
        [arr addObject:dict];
        [elementsInSection setObject:arr atIndexedSubscript:[sections indexOfObject:day]];
    }
}

And your tableview datasource is now become

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [elementsInSection count];
}
Comments