UITableView实现加载更多功能

来源:互联网 发布:淘宝要怎么运营 编辑:程序博客网 时间:2024/05/17 21:40

UITableview能够列表显示许多内容,也是我们开发中经常用的一个组件。我们经常会分页显示列表,如先显示10条记录,点击更多在添加10条,以此类推,下面是实现类似更多显示的一个demo。

实现的思路:

  • 基本上就是数据源里先只放10条, 点击最后一个cell时, 添加更多的数据到数据源中.。
  • 处理"加载更多"的那个cell的选择事件,触发一个方法来加载更多数据到列表。
  • indexPathForRow插入数据。
数据源是个array:

NSMutableArray *items;

ViewController的这个方法返回数据条数: +1是为了显示"加载更多"的那个cell

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int count = [items count];
return count + 1;
}

这个方法定制cell的显示, 尤其是"加载更多"的那个cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if([indexPath row] == ([items count])) {
//创建loadMoreCell

return loadMoreCell;
}

//create your data cell

return cell;
}

还要处理"加载更多"的那个cell的选择事件,触发一个方法来加载更多数据到列表

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if (indexPath.row == [items count]) {
[loadMoreCell setDisplayText:@"loading more ..."];
[loadMoreCell setAnimating:YES];
[self performSelectorInBackground:@selector(loadMore) withObject:nil];
//[loadMoreCell setHighlighted:NO];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
return;
}

//其他cell的事件

}

加载数据的方法:

-(void)loadMore
{
NSMutableArray *more;
//加载你的数据
[self performSelectorOnMainThread:@selector(appendTableWith:) withObject:more waitUntilDone:NO];
}

添加数据到列表:

-(void) appendTableWith:(NSMutableArray *)data
{

for (int i=0;i<[data count];i++) {
[items addObject:[data objectAtIndex:i]];
}
NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:10];
for (int ind = 0; ind < [data count]; ind++) {
NSIndexPath *newPath = [NSIndexPath indexPathForRow:[items indexOfObject:[data objectAtIndex:ind]] inSection:0];
[insertIndexPaths addObject:newPath];
}
[self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];

}
原创粉丝点击