对表视图进行分组与分区,便于用户对信息的查找。首先需要创建.plist的文件,包含所有的信息,便于表视图加载过程中数据的录入。用字典存储,以数组的方式获取表视图的数据。遵循UITableViewDelegate协议实现对表视图的分区。
首先添加、编写.plist文件,写入数据,也可导入:
在.h文件中添加协议,创建对象:
- @interface LinViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
- //创建表视图的对象
- @property (retain, nonatomic) UITableView * mTableView;
- //创建字典对象
- @property (retain, nonatomic) NSDictionary * mDictionary;
- //创建数组对象
- @property (retain, nonatomic) NSArray * mArray;
-
- @end
在.m文件里添加实现的方法:
- @implementation LinViewController
-
- //释放创建的对象
- - (void)dealloc
- {
- [_mTableView release];
- [_mDictionary release];
- [_mArray release];
- [super dealloc];
- }
- //加载视图
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- //创建初始化表视图
- self.mTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
- //设置委托对象
- self.mTableView.dataSource = self;
- self.mTableView.delegate = self;
- //把表视图加载到当前视图中
- [self.view addSubview:self.mTableView];
-
- //获取.plist文件的路径
- NSString * path = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"];
- //初始化字典
- self.mDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
- //初始化数组,根据字典对象获取的数据
- self.mArray = [[self.mDictionary allKeys]sortedArrayUsingSelector:@selector(compare:)];
- //此处关联的方法是排列方式显示的方法,此时表示按字母顺序排列
- }
- #pragma mark---UITableViewDataSource---------
- //根据数组元素获取表视图的行数
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- return [[self.mDictionary objectForKey:[self.mArray objectAtIndex:section]]count];
- }
- //绘制每一行表
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- //设置一个静态字符串做标签,(静态防止局部变量多次创建,提高效率,节约内存)
- static NSString * identifer = @"identifer";
- //创建一个cell对象(利用表示图可以复用的机制)
- UITableViewCell * pCell = [tableView dequeueReusableCellWithIdentifier:identifer];
- //如果cell为空,就创建一个新的出来
- if (nil == pCell)
- {
- pCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
- }
- //获取所在的区域
- NSInteger section = [indexPath section];
- //获取当前表视图行数
- NSInteger row = [indexPath row];
- //把数组中对应元素传递给视图的文本
- pCell.textLabel.text = [[self.mDictionary objectForKey:[self.mArray objectAtIndex:section]]objectAtIndex:row];
- return pCell;
- }
- //显示区域的表头标题
- - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
- {
- return [self.mArray objectAtIndex:section];
- }
- //显示区域的索引
- - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
- {
- return self.mArray;
- }
- #pragma mark---UITableViewDelegate-----------
- //为表视图分区
- - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- {
- return [self.mArray count];
- }
-
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- }
- end
|