按照UITable学习一中,继续往下开发。使用的资料在UITable学习一中。
具体代码如下:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> @property(retain) NSDictionary * names; @property (retain) NSArray * keys; @end
#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:@"sortednames" ofType:@"plist"]; NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:path]; self.names = dict; [dict release]; //获得字典关键字数组,然后排序,其中compare方法是字典中的key的compare方法 NSArray *array = [[self.names allKeys]sortedArrayUsingSelector:@selector(compare:)]; self.keys = array; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{ // return TRUE; //} //设置多少个分区 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ //按照关键字分区,关键字个数也是分区个数 return [self.keys count]; } //每种分区有多少数据 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ //根据分区序号,找到关键字 NSString *key = [self.keys objectAtIndex:section]; //在字典中找到所有的关键字为key的名字,放到一个数组中 NSArray *nameSection = [self.names objectForKey:key]; //数组中元素的个数 return [nameSection count]; } //设置每行的数据 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *idt = @"sectionTableIndentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:idt]; if(cell == nil){ cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idt]; } NSUInteger section = [indexPath section]; NSUInteger row = [indexPath row]; NSString *key = [self.keys objectAtIndex:section]; NSArray *nameSection = [self.names objectForKey:key]; cell.textLabel.text = [nameSection objectAtIndex:row]; return cell; } //返回每个分区的标题 -(NSString*)tableView:(UITableView*) tableView titleForHeaderInSection:(NSInteger)section{ NSString *key = [self.keys objectAtIndex:section]; return key; } //添加索引 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{ return self.keys; } @end