分组表中每个分组都是一个分区,在索引表中,每个索引都是一个分区。
实现一个简单的表:
首先在xib文件中拖入一个tableview,将其dataSource和delegate连接到File‘s owner
@interface Hello_WorldViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>{
}
上述代码的作用是让类遵循两个协议,类需要这两个协议来充当表现图的委托和数据源,数据源提供了绘制表所需要的所有数据,委托用于配置表视图的外观 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.listData.count; } 上述方法用来指明该section有几个表项,默认section值为1
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier=@"simpleIdentifier"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if(cell==nil) { cell=[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:simpleTableIdentifier]; } NSUInteger row=[indexPath row]; cell.text=[self.listData objectAtIndex:row]; return cell; }
上述函数用来绘cell,第一个参数是代表用来绘cell的发起者,第二个参数是indexPath,通过该参数我们可以得到section和row,
表视图在iphone上一次只能显示有限的几行,但是表示图的数据量可以是很大的,如果我们为每一行数据量分配一个cell,那么开销将非常大。
同时我们发现,有些cell是当前显示,有些不是,当一个cell滚出屏幕时,另一些cell就会从另一边滚到屏幕上,如果滚到屏幕上的cell重新使用滚出屏幕的cell,那么系统就不会为创建或删除一个新的cell而浪费空间与时间。我们用simpleTalbeIdentifier来标示每个cell,调用[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier] ,看有这个标示的cell是否以前在可重用队列中出现过,如果有那直接使用即可,如果没有则为nil,cell=[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:创建新的cell。
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath { NSUInteger section=[indexPath row]; NSLog(@"setion is %d",section); NSString *rowValue=[self.listData objectAtIndex:section]; UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"你选择的是" message:rowValue delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil]; [alertView show]; } 上述方法表示点击一个cell时调用
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 100; }
上述方法根据indexPath给出每个cell的高度
|