Wednesday, 19 June 2013

Table View With Section (Grouped Table View)

For grouped tableview fallow the following steps...

1. Create new Project.
2. Drag a uitableview from object library.
3. Change the style of uitableview from plain(default) to grouped from selecting the attribute inspector..
4. Make the chenges in .h file


@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray* arrPhysics;
    NSMutableArray* arrMathematics;
    NSMutableArray* arrHeader;
}
@property (strong, nonatomic) IBOutlet UITableView *tblWithSections;

5.Make the changes in .m file

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    NSDateFormatter* format = [[NSDateFormatter alloc]init];
    NSString* strDate = @"20/06/2013";
    [format setDateFormat:@"dd.MM.yyyy"];
    NSLog(@"%@", [format dateFromString:strDate]);
    
    
    arrHeader = [[NSMutableArray alloc]initWithObjects:@"Physics",@"Math", nil];
    arrPhysics = [[NSMutableArray alloc]initWithObjects:@"Amit",@"Sudheer", nil];
    arrMathematics = [[NSMutableArray alloc]initWithObjects:@"Kiran",@"Vijay", nil];
    
// Do any additional setup after loading the view, typically from a nib.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [arrHeader count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
    {
        return [arrPhysics count];
    }
    else if(section==1)
    {
        return [arrMathematics count];
    }
    else
        return 0;
}

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [arrHeader objectAtIndex:section];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdent;
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdent];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdent];
    }
    if(indexPath.section==0)
    {
        cell.textLabel.text = [arrPhysics objectAtIndex:indexPath.row];
    }
    else
    {
        cell.textLabel.text = [arrMathematics objectAtIndex:indexPath.row];
    }
    return cell;
}

6. Make sure the neccessary connection like UITableViewDelegate and UITableview Datasource.

No comments:

Post a Comment