MainViewController.h
@interface RootViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> @property(nonatomic, retain)NSDictionary *dic; @property(nonatomic, retain)NSArray *allKeys;
MainViewController.m
- (void)viewDidLoad { [super viewDidLoad]; //创建表视图 UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 460) style:UITableViewStylePlain]; tableView.delegate = self; tableView.dataSource = self; [self.view addSubview:tableView]; [tableView release]; NSString *path = [[NSBundle mainBundle] pathForResource:@"ListData.plist" ofType:nil];// /ListData.plist _dic = [[NSDictionary alloc] initWithContentsOfFile:path]; //取得key // _allKeys = [_dic allKeys]; /* sortedArrayUsingSelector:遍历数组中的每一个元素,调用后面的方法 */ _allKeys = [[[_dic allKeys] sortedArrayUsingSelector:@selector(compare:)] retain]; //设置侧栏的背景颜色 tableView.sectionIndexBackgroundColor = [UIColor blackColor]; } /* 字典的结构 A : ["asd","ase","aer","add"], B : ["bsd","bse","br","bd"], C : ["cc","cd"], ...... */ #pragma mark - UITableView dataSource //设置组的个数 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return _dic.count; } //设置每组有多少个cell - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSString *key = [_allKeys objectAtIndex:section]; NSArray *value = [_dic objectForKey:key]; return value.count; } //创建cell - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *inde = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:inde]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inde] autorelease]; } NSString *key = [_allKeys objectAtIndex:indexPath.section]; NSArray *value = [_dic objectForKey:key]; cell.textLabel.text = value[indexPath.row]; return cell; } //设置组的头视图标题 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return [_allKeys objectAtIndex:section]; } - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return _allKeys; } //点击右侧索引栏调用的方法 //返回的是组的索引 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { NSLog(@"title:%@",title); NSInteger a = [_allKeys indexOfObject:title]; return a + 2; }
时间: 2024-11-09 07:31:17