前语:
手动上拉更新确实是个好东西,但是本人不喜欢。因为当我阅读完当前的数据的时候,还要上拉一下,等待刷新,这个对浏览信息来说是一个很蛋疼的事情。
下面介绍一下很简单的一个自动刷新的方法:
在UITableView delegate实现方法里面
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSInteger row = [indexPath row];
/*
* _NumberOfUserRequestData 是当前你请求成功了多少页的数据。
* _NumberOfOption 是数据的总页数。
* 该if语句判断是否还有可以刷新的数据
*/
if (_NumberOfUserRequestData<_NumberOfOption) {
if (row==(numberOfCell-5)&&[_request isFinished]) {
/*
* (numberOfCell-5) 如果当用户滑动到倒数第五个。
* [_request isFinished] _request设置为全局变量,而且当前请求已经结束的时候
* 该句判断当用户滑动到第5个cell,并且当上次数据加载完成、
*/
[self loadMoreData]; //获取更多数据方法、
}
}
}
当然要处理一下UITableView的总个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSInteger count =self.bookTitleArray.count; //总的cell个数、
if (count ==0) {
return0;
}
if (_NumberOfUserRequestData<_NumberOfOption) {
//如果还有可刷新的数据、返回cell的个数是多一个
return count +1;
}
return count;
}
moreCell为自定义的Cell,控件有stateLabel,小齿轮moreCellActivityIndicatorView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSInteger row = [indexPath row];
if(row == _bookTitleArray.count) {
static NSString *MoreCellIdentifier =@"TableMoreCell";
TableMoreCell *moreCell = [tableView dequeueReusableCellWithIdentifier:MoreCellIdentifier];
if (!moreCell) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"TableMoreCell"owner:self options:nil];
moreCell = [nib objectAtIndex:0];
}
if (![_request isFinished]) { //当前请求还没有结束的话显示小齿轮
/*-------加载小齿轮--------*./
moreCellActivityIndicatorView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(70,12,20,20)];
moreCellActivityIndicatorView.activityIndicatorViewStyle =UIActivityIndicatorViewStyleGray;
moreCellActivityIndicatorView.hidesWhenStopped =YES;
[moreCellActivityIndicatorView startAnimating];
[moreCell addSubview:moreCellActivityIndicatorView];
moreCell.stateLabel.text =@"正在加载";
}else{
moreCell.stateLabel.text =@"点击查看更多";
}
return moreCell;
} else {...........//正常cell的样式处理}
}
效果图:
如果滑动的慢,有刷新的数据,网速快的情况下,用户一直都不用手动去刷新,等到他还没有拉到最低端的时候,已经加载出了新的数据
如果想等到用户拉到最低端在进行加载数据的话:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if(tableView.contentOffset.y+ (tableView.frame.size.height)
> tableView.contentSize.height){
//method
}
}