表视图,应该是我们的应用中使用对多的控件之一.今天我们就简单说下如何建立一个表视图.
学习完表视图之后,我认为如下几点值得注意:
1)数据源 datasource 和delegate 与 file's owner 之间的连接
2)数据源的两种实现方式:在viewdidload 中加载 固定数据 和 使用 plist 读取文件数据
3)实现 <UITableViewDataSource ,UITableViewDelegate >中的一些 必须实现的函数.
1.由于第一条属于拖拽性质的,就不再赘述.
2. i: viewDidLoad 中加载固定数据
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *array = [[NSArray alloc]initWithObjects:@"lichan",@"xuna",@"liyang",@"zhaomingwei",@"dhuang",@"laoer",@"lichan",@"xuna",@"liyang",@"zhaomingwei",@"dhuang",@"laoer",@"lichan",@"xuna",@"liyang",@"zhaomingwei",@"dhuang",@"laoer", nil];
self.listData =array;
// Do any additional setup after loading the view, typically from a nib.
}
ii: 使用plist 文件加载数据
- (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 *dic = [NSDictionary dictionaryWithContentsOfFile:path];
self.names = dic;
NSArray *array = [[names allKeys]sortedArrayUsingSelector:@selector(compare:)];
self.keys = array;
}
3.实现
<UITableViewDataSource,UITableViewDelegate> 的协议函数.
当我们建立一个表的时候,我们应该考虑如下几点:
1)我们的表有多少列?多少行?
这就需要实现UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
NSArray *nameSelection = [names objectForKey:key];
return [nameSelection count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [keys count];
}
2)tableView里面的cell是如何加载的 ?
这个实现函数在 UITableViewDelegate 里.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger section = [indexPath section];
NSInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *namesection = [names objectForKey:key];
static NSString *sectionsTableIdentifier = @"selectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionsTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionsTableIdentifier];
}
cell.textLabel.text = [namesection objectAtIndex:row];
return cell;
}
4.经过上述几个步骤,我们的简单的表视图就呈现在我们面前了.
下一篇,将介绍 视图之间的分组分区和索引分区.