首先需要在xib的视图文件中修改TableView的style中选择Grouped。
然后实现2个方法
1. numberOfSectionsInTableView,分多少个组。
2. titleForHeaderInSection 每个组的title
具体代码如下
省略Property List文件test.plist
// // ViewController.h // TableView1 // // Created by Rayln Guan on 9/22/13. // Copyright (c) 2013 Rayln Guan. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> @property(nonatomic,retain) NSDictionary *dic; @property(nonatomic,retain) NSArray *arr; @end
// // ViewController.m // TableView1 // // Created by Rayln Guan on 9/22/13. // Copyright (c) 2013 Rayln Guan. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"plist"]; self.dic = [[NSDictionary alloc] initWithContentsOfFile:path]; self.arr = [self.dic allKeys]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSLog(@"section:%i", section); return [self.dic count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ //UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; //一种提升性能的做法 //[indexPath section]获取section UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if(cell == nil){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"]; } NSString *key = [self.arr objectAtIndex:[indexPath row]]; [[cell textLabel] setText:[self.dic objectForKey:key]]; //detail [[cell detailTextLabel] setText:@"detail"]; //设置cell样式, 比如这个,在右侧增加一个箭头 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; //[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton]; //设置一个图片 NSString *path = [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"]; UIImage *img = [[UIImage alloc]initWithContentsOfFile:path]; [[cell imageView]setImage:img]; return cell; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 2; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ if(section == 0){ return @"title1"; }else{ return @"title2"; } } - (void)dealloc { NSLog(@"destory!!"); [_dic release]; [_arr release]; [super dealloc]; } @end