首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

TableView 的施用 实例一

2012-09-14 
TableView 的使用 实例一TableView 是iphone/ipad中常常会用到的导航控件,本实例我们开始做一个基本的导航

TableView 的使用 实例一
TableView 是iphone/ipad中常常会用到的导航控件,本实例我们开始做一个基本的导航菜单列表,通过该例可以让大家了解该控件的基础知识及基本使用的方法,废话少说开始。

一、首先我们先创建一个iphone或ipad工程(本例以iphone为例)命名TableViewDemo1
如下图所示:



二、打开TableViewDemo1ViewController.xib,添加TableView控件。



三、编辑TableViewDemo1ViewController.h
      添加实现的协议UITableViewDelegate,UITableViewDataSource,及声明UITableView对象tableViewList

@interface TableViewDemo1ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> {IBOutlet UITableView *tableViewList;}@end


四、打开TableViewDemo1ViewController.xib,IB设计器使TableView控件与之前声明的对象tableViewList做关联。


打开以上窗口,右键选中File's Owner并拖动至Table View上

在弹出菜单中选tableViewList
然后再右键选中Table View拖至File's Owner,淡出菜单如下

分别选中dataSource和delegate


至此IB设计完毕,下一步我们会在类中添加导航的实现代码。

五、添加实现代码
打开编辑TableViewDemo1ViewController.h
添加 NSMutableArray *dataItems;
@interface TableViewDemo1ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> {IBOutlet UITableView *tableViewList;NSMutableArray *dataItems;}@end


打开编辑TableViewDemo1ViewController.m
在viewDidLoad中初始化dataItems
- (void)viewDidLoad {    [super viewDidLoad];dataItems=[[NSMutableArray alloc]initWithObjects:@"中国",@"美国",@"日本",nil];}


添加数据源, 由三个函数来回答数据绑定的请求:numberOfSectionsInTableView, numberOfRowsInSection 和 cellForRowAtIndexPath.
用numberOfSectionsInTableView方法来返回table中有几个组.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{  return 1;}

用numberOfRowsInSection方法来返回每个组里有几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  return [dataItems count]; }

最后用cellForRowAtIndexPath来得到一个包含每一行显示信息的UITableViewCell对象. UITableViewCell类支持文本和图像,编辑和删除确认等功能. 这些信息会保存在表队列里,用来至此翻页等功能,但是内存很低的时候会自动释放,然后再需要的时候重新创建.
// Customize the appearance of table view cells.- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {        static NSString *CellIdentifier = @"Cell";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];    if (cell == nil) {        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];    }NSUInteger row=[indexPath row];cell.textLabel.text=[dataItems objectAtIndex:row];    return cell;}


OK至此最基本的导航菜单我们算是完成了,运行一下看看效果


本例先搞一段落TableView更加丰富多彩的应用会在以后例子中继续讲解,
实例代码可见附件TableviewDemo1.zip
      1 楼 kkun 2012-06-13   学习了。。。

热点排行