UITableView 创建带索引的二级列表:
本例所创建的二级列表信息为:
第一级:国家(魏国,蜀国,吴国)-kingdoms;
第二级:武将(各个国家的主要武将)-heros;
ps:国家&武将信息量较大,创建两个plist文件分别用于储存国家信息(NSArray)和武将信息(NSDictionary),然后再代码中将plist信息加载到对应的数组/字典;
主要代码如下:
ViewController.h文件:
|
1
2
3
4
5
6
7
8 |
#import <UIKit/UIKit.h> @interface
ViewController : UIViewController<UITableViewDataSource> @property(nonatomic, strong)NSArray
*kingdoms; // 国家@property(nonatomic, strong)NSDictionary
*heros; // 武将 @end |
ViewController.m文件:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 |
#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寸屏):

UITableView:创建带索引的二级列表,布布扣,bubuko.com
原文:http://www.cnblogs.com/fizix100/p/3678757.html