UITableView ──分页加载

IOS开发UI展示之UITableView ──分页加载

在ios开中中,由于屏幕尺寸限制,如果需要显示的数据很多,需要用到分页加载。

原理:先数据放到一个table中,先显示10条,table底部有一察看更多选项,点击察看更多查看解析的剩余数据。基本上就是数据源里先只放10条, 点击最后一个cell时, 添加更多的数据到数据源中. 比如:

数据源是个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];

}

我这里是写死的数据,作例子,在实现工程项目中,比如:要向服务器请求数据,一般返回数据会有总共多少页,一次请求一页,当用户需要看更多页面时,滑动到最下面cell,再请求下一面!

我这里例子,请求加载更多是写到didSelectRowAtIndexPath:代理方法中,如果需要自动加载,可以放到- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

代理方法中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 12,977评论 3 38
  • 前言 最近忙完项目比较闲,想写一篇博客来分享一些自学iOS的心得体会,希望对迷茫的你有所帮助。博主非科班出身,一些...
    GitHubPorter阅读 5,330评论 9 5
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 9,198评论 2 7
  • 神风说,他爱上一个姑娘只需要2秒钟。 我问她,你爱过多少个姑娘? 她说,两个,她自己算其中1个。 我问她,另外一个...
    燕山寒羽阅读 1,382评论 2 1
  • 今天起来早,去市图书馆时门还没有开,但队排已经排的很长了。跳广场舞阿姨很精神,吹笛子的大哥也很带劲。美好的生...
    雷一凡阅读 1,355评论 0 0

友情链接更多精彩内容