How do I divide sections in UITableView?

how can i divide sections in tableview? below is the code i tried to divide but unable to get the sections..

#import "ipapbatch3ViewController.h"  

@implementation ipapbatch3ViewController    

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section  
{  
    NSInteger numberofrows=5;    
    return numberofrows;  

}  

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath    
{
    NSArray *a = [NSArray arrayWithObjects:@"rams",@"balu",@"praveen",@"sagar",@"faizan",nil];    
    UITableViewCell * r = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];    
    [r autorelease];  

    r.textLabel.text=[a objectAtIndex:[indexPath row]];  

                         return r;  
                         }  
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView      
{    
    NSInteger sc = 2;      
    return sc;    

}    




@end  

Upvotes: 1

Views: 2236

Answers (2)

Cyprian
Cyprian

Reputation: 9453

Your main problem in the code above is that you never tell which section to inser new cell, and thus they all fell into the first one. Look into the method cellForRowAtIndexPath you need to specify that the newly created cell goes to a particular section.

Go through those example programs provided by apple.

Upvotes: 0

Nick Weaver
Nick Weaver

Reputation: 47241

It's all in the cellForRowAtIndexPath, here's a small example:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath    
{
    UITableViewCell * r = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];

    if (indexPath.section == 0) {
        NSArray *a = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",nil];    
        r.textLabel.text = [a objectAtIndex:indexPath.row];  

    } else {
        NSArray *b = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",nil];    
        r.textLabel.text = [b objectAtIndex:indexPath.row];  

    }

    return r;  
}

Upvotes: 3

Related Questions