Firdous
Firdous

Reputation: 4652

Custom UITableViewController structure

I am making a custom table view which has content 'Static Cells' and style 'Grouped'. I want to insert static contents programatically. I can do init the view by:

MyCustomViewController *myCustomViewController = [[MyCustomViewController alloc] init];
[self.navigationController pushViewController:myCustomViewController animated:TRUE];

I want to make 3 sections in the table view, one section having 2 cells and the other two sections having 1 cell. Have populated dynamics cells previously but no idea on how to deal with this creation of sections and varying number of cells within. Any solutions?

enter image description here

Upvotes: 0

Views: 435

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130212

This should help you!

- (void)viewDidLoad
{

    [super viewDidLoad];

    NSArray *firstSection = [NSArray arrayWithObjects:@"Red", @"Blue", nil];
    NSArray *secondSection = [NSArray arrayWithObjects:@"Orange", @"Green", @"Purple", nil];
    NSArray *thirdSection = [NSArray arrayWithObject:@"Yellow"];

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:firstSection, secondSection, thirdSection, nil];
    [self setContentsList:array];
    array = nil;


}
- (void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    NSInteger sections = [[self contentsList] count];

    return sections;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{

    NSArray *sectionContents = [[self contentsList] objectAtIndex:section];
    NSInteger rows = [sectionContents count];

    NSLog(@"rows is: %d", rows);
    return rows;
}

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

    NSArray *sectionContents = [[self contentsList] objectAtIndex:[indexPath section]];
    NSString *contentForThisRow = [sectionContents objectAtIndex:[indexPath row]];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }

    [[cell textLabel] setText:contentForThisRow];

    return cell;
}

#pragma mark -
#pragma mark UITableView Delegate Methods

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

Upvotes: 1

Related Questions