Corona中文站

强大、易学的跨平台(iOS/Android)开发框架。QQ群1:74390406(满) 群2:221929599

导航

编写简单的TableView
在iOS下编写TableView是很容易的。
最简单的TableView比如实现这样的效果:

首先创建一个view based application:



接着,修改view xib文件,将TableView拖拽到view中:

右侧图是拖拽后的效果。然后是建立关联,需要建立两个:

dataSource,连接到数据源,这样TableView才知道显示数据的信息
delegate,连接到TableView delegate,回调它来和应用的逻辑部分交互

都连接到Controller即可,即file’s owner:

然后,需要让Controller实现两个protocol:

@interface TableDemoViewController : UIViewController

其中UITableViewDataSource要求两个方法必须实现:

这里要先在h文件中声明用于dataSource的数据结构,这是使用的是固定数组:

NSArray *dataItems;
}
@property(nonatomic,retain) NSArray *dataItems;

然后,在m文件中实例化数组:

@synthesize dataItems;

- (void)viewDidLoad {
dataItems= [[NSArray alloc] initWithObjects:@"张三",@"李四",nil];
[super viewDidLoad];
}

现在可以实现上面的两个方法了:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [dataItems count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier=@"SimpleTableIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell==nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier] autorelease];
}
NSUInteger row=[indexPath row];
cell.textLabel.text=[dataItems objectAtIndex:row];
return cell;
}

这里要注意,我写的例子是参照《iPhone开发基础教程》,里面的写法是:

cell.text=…

已经不建议使用了:

在TableView条目前添加图片

如果想实现这样的效果:

这里的图片,来自项目自身,可以将图片拖拽到项目的Resources目录下:

然后在代码中只需增加一行:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier=@"SimpleTableIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(cell==nil){
cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier] autorelease];
}
NSUInteger row=[indexPath row];
cell.textLabel.text=[dataItems objectAtIndex:row];
cell.imageView.image=[UIImage imageNamed:@"tag.png"];
return cell;



为TableView增加交互功能只需增加一个函数即可,这是UITableViewDelegate protocol中的一个函数,用于在选择表条目后回调。

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@">>choose:%@",[dataItems objectAtIndex:[indexPath row]]);
}
<< iPhone中定时器NSTimer使用方法XCode中的快捷键 >>

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最近发表

Powered By Z-Blog 1.8 Walle Build 100427 Copyright 2011-2015 BuildApp.Net. All Rights Reserved.