`
toyota2006
  • 浏览: 545223 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

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
     
  • 大小: 79.4 KB
  • 大小: 31.5 KB
  • 大小: 27.9 KB
  • 大小: 29.4 KB
  • 大小: 32.9 KB
  • 大小: 19.8 KB
  • 大小: 95.1 KB
2
2
分享到:
评论
1 楼 kkun 2012-06-13  
学习了。。。

相关推荐

Global site tag (gtag.js) - Google Analytics