tableview协议,如果指明遵循这个协议,一下三个函数是一定要在viewcontroller里实现的
(1)numberOfSectionsInTableView:
告知视图,有多少个section需要加载到table里
(2)tableView:numberOfRowsInSecion:
告知controller每个section需要加载多少个单元或多少行
(3)tableView:cellForRowAtIndexPath:
返回UITableViewCell的实例,用于构成table view.这个函数是一定要实现的。
实现的例子
data source与delegate的区别
data source用于提供数据给table view. 当事件发生时,table view向delegate请求,或者当table view需要更多的信息时。
例如在以下情况下将调用delegate函数
(1)在一个单元被选中或不再选中
(2)当视图需要获得每个单元的高度
(3)当视图需要构建每个section的头部及尾部
(1)numberOfSectionsInTableView:
告知视图,有多少个section需要加载到table里
(2)tableView:numberOfRowsInSecion:
告知controller每个section需要加载多少个单元或多少行
(3)tableView:cellForRowAtIndexPath:
返回UITableViewCell的实例,用于构成table view.这个函数是一定要实现的。
实现的例子
点击(此处)折叠或打开
- - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- {
- NSInteger result = 0;
- if ([tableView isEqual:self.myTableView]){
- result = 3;
- }
- return result;
- }
点击(此处)折叠或打开
- - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- {
- NSInteger result = 0;
- if ([tableView isEqual:self.myTableView]){
- switch (section){
- case 0:{
- result = 3;
- break;
- }
- case 1:{
- result = 5; break;
- }
- case 2:{
- result = 8;
- break;
- }
- }
- }
- return result;
- }
-
点击(此处)折叠或打开
- - (UITableViewCell *) tableView:(UITableView *)tableView
- cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- UITableViewCell *result = nil;
- if ([tableView isEqual:self.myTableView]){
- static NSString *TableViewCellIdentifier = @"MyCells";
- result = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
- if (result == nil){
- result = [[UITableViewCell alloc]
- initWithStyle:UITableViewCellStyleDefault
- reuseIdentifier:TableViewCellIdentifier];
- }
- result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",
- (long)indexPath.section,
- (long)indexPath.row];
- }
- return result;
- }
data source用于提供数据给table view. 当事件发生时,table view向delegate请求,或者当table view需要更多的信息时。
例如在以下情况下将调用delegate函数
(1)在一个单元被选中或不再选中
(2)当视图需要获得每个单元的高度
(3)当视图需要构建每个section的头部及尾部