UITableView:创建带索引的二级列表
UITableView 创建带索引的二级列表:
本例所创建的二级列表信息为:
第一级:国家(魏国,蜀国,吴国)-kingdoms;
第二级:武将(各个国家的主要武将)-heros;
ps:国家&武将信息量较大,创建两个plist文件分别用于储存国家信息(NSArray)和武将信息(NSDictionary),然后再代码中将plist信息加载到对应的数组/字典;
主要代码如下:
ViewController.h文件:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDataSource> @property(nonatomic, strong)NSArray *kingdoms; // 国家 @property(nonatomic, strong)NSDictionary *heros; // 武将 @end
ViewController.m文件:
#import "ViewController.h" @implementation ViewController @synthesize kingdoms,heros; - (void)viewDidLoad { [super viewDidLoad]; NSBundle *bundle = [NSBundle mainBundle]; // 加载数据 self.kingdoms = [NSArray arrayWithContentsOfFile:[bundle pathForResource:@"kingdoms" ofType:@"plist"]]; self.heros = [NSDictionary dictionaryWithContentsOfFile:[bundle pathForResource:@"heros" ofType:@"plist"]]; } // 返回第一级列表item数量 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return kingdoms.count; } // 返回第一级列表对应item的值 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return kingdoms[section]; } // 返回第二级列表item数量 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSString *kingdom = kingdoms[section]; NSArray *iHeros = heros[kingdom]; return iHeros.count; } // // 返回第二级列表对应item的值 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; { UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; NSString *kingdom = kingdoms[indexPath.section]; NSArray *iHeros = heros[kingdom]; cell.textLabel.text = [iHeros objectAtIndex:indexPath.row]; return cell; } // 在列表右部显示索引列表的方法 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return kingdoms; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; [kingdoms release],kingdoms = nil; [heros release],heros = nil; } @end
模拟器运行效果(3.5寸屏):