1
2
3
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
}
這種方法沒法實現的 這種方法確實能判斷滑動到最后 但是加載數據時 這個方法又回被調用 造成無限循環 所以不建議使用
這里我使用的是這個方法
1
2
3
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
}
具體代碼
定義一個全局變量
@()bool ;
來標示是否正在加載數據
然后根據滑動的高度做判斷 看是否滑動到了底部
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
- (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
isNeedLoadMore = true;
}
}else{
//當currentOffset與maximumOffset的值相差很小時,說明scrollview已經滑到底部了。
CGFloat space = currentOffset - maximumOffset;
if(space>minSpace && space
isNeedLoadMore = true;
}
}
if(!self.isLoading && isNeedLoadMore){
self.isLoading = true;
NSLog(@"-->加載更多數據");
[self loadMore];
}
}
但是有這樣一個問題 如果已經確認沒有更多數據的時候 我們會在加載更多的方法里直接設置self. = false;
但是由于視圖動畫還在滑動就會反復觸發加載更多的方法
解決方法就是延遲設置self. = false;
1
2
3
4
5
[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;
});
這樣就能確保不會多次加載了