[新手学ios]第四天:简历一个简单的表视图.

表视图,应该是我们的应用中使用对多的控件之一.今天我们就简单说下如何建立一个表视图.

学习完表视图之后,我认为如下几点值得注意:

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.经过上述几个步骤,我们的简单的表视图就呈现在我们面前了.

下一篇,将介绍 视图之间的分组分区和索引分区.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值