利用UITableView创建最简单的表视图。就是每一列中显示一行文字。效果图如下:
表视图并不负责存储数据,只是负责展示相关的内容,表视图中遵循UITableViewDelegate和 UITableViewDataSource协议。
首先创建一个视图项目:
声明代码:
#import <UIKit/UIKit.h>
@interface iphone_tableviewViewController : UIViewController
<UITableViewDelegate,UITableViewDataSource>{
NSArray * listData;
}
@property ( nonatomic, retain) NSArray *listData;
@end
实现代码:
#import “iphone_tableviewViewController.h”
@implementation iphone_tableviewViewController
@synthesize listData;
- (void )viewDidLoad {
NSArray *array= [[ NSArray alloc ] initWithObjects : @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, @”你好 “, nil ];
self .listData =array;
[array release ];
[ super viewDidLoad];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void )didReceiveMemoryWarning {
// Releases the view if it doesn’t have a superview.
[ super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren’t in use.
}
- (void )viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void )dealloc {
[ listData release ];
[super dealloc ];
}
// 添加行数
-(NSInteger ) tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger )section
{
return [ self. listData count ];
}
// 添加每一行的信息
- (UITableViewCell *) tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *tag=@”tag” ;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tag];
if (cell==nil ) {
cell=[[[ UITableViewCell alloc ] initWithFrame : CGRectZero
reuseIdentifier:tag] autorelease];
}
NSUInteger row=[indexPath row ];
cell.text =[listData objectAtIndex :row];
return cell;
}
@end
最后打开Interface Builder,添加相应的视图,并且相关联:
编译运行既可。
官方文档:
源代码: http://easymorse.googlecode.com/svn/trunk/iphone.tableview/