天天看點

iOS UITableView 滑動到底部加載更多資料

前言

很多APP都是滑動到底部時點選加載更多才會加載資料,這樣使用者體驗就會有間斷感,是以我們想使用者看到最後時自動加載資料 怎麼做呢

有人會說用一下的這個方法

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

}           

複制

這種方法

沒法實作

的 這種方法确實能判斷滑動到最後 但是加載資料時 這個方法又回被調用 造成無限循環 是以不建議使用

這裡我使用的是這個方法

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

}           

複制

具體代碼

定義一個全局變量

@property(nonatomic)bool isLoading;

來标示是否正在加載資料

然後根據滑動的高度做判斷 看是否滑動到了底部

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    CGFloat scrollViewHeight = bounds.size.height;
    CGFloat currentOffset = offset.y + scrollViewHeight - inset.bottom;
    CGFloat maximumOffset = size.height;
    
    CGFloat minSpace = 5;
    CGFloat maxSpace = 10;
    bool isNeedLoadMore = false;
    //上拉加載更多
    //tableview 的 content的高度 小于 tableview的高度
    if(scrollViewHeight>=maximumOffset){
        CGFloat space = currentOffset - scrollViewHeight;
        if(space>minSpace && space <maxSpace){
            isNeedLoadMore = true;
        }
    }else{
        //當currentOffset與maximumOffset的值相差很小時,說明scrollview已經滑到底部了。
        CGFloat space = currentOffset - maximumOffset;
        if(space>minSpace && space <maxSpace){
            isNeedLoadMore = true;
        }
    }
    
    if(!self.isLoading && isNeedLoadMore){
        self.isLoading = true;
        NSLog(@"-->加載更多資料");
        [self loadMore];
    }
}           

複制

但是有這樣一個問題 如果已經确認沒有更多資料的時候 我們會在

加載更多

的方法裡直接設定

self.isLoading = false;

但是由于視圖動畫還在滑動就會反複觸發

加載更多

的方法

解決方法就是延遲設定

self.isLoading = false;

[SVProgressHUD showErrorWithStatus:@"沒有更多資料了"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  [SVProgressHUD dismiss];
  self.isLoading = false;
});           

複制

這樣就能確定不會多次加載了