在使用table view獲取列表資料時,若一次將資料全數拉回,
當資料量大的時候會消耗非常久的時間,
因此常常會將資料分裝成一個個「桶子」,比如說一桶有20筆資料,
一次只向server要20筆資料,就不會發生讀資料讀到天荒地老的狀況,
而向server要資料的時機點除了一開始的初始資料以外,
在使用者滑動列表到最下方時,才開始讀取下一段資料。
有幾個方法可以判斷table view/collection view需要load下一筆資料:
一、利用cellForItemAtIndexPath delegate
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == datasourceArray.count - 1) { // load more data } }
需要多加一個布林值判斷是否需要load更多資料,
以避免重複打server api造成資源浪費。
二、利用scroll view的content offset
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView { CGPoint offset = aScrollView.contentOffset; CGRect bounds = aScrollView.bounds; CGSize size = aScrollView.contentSize; UIEdgeInsets inset = aScrollView.contentInset; float y = offset.y + bounds.size.height - inset.bottom; float h = size.height; // NSLog(@"offset: %f", offset.y); // NSLog(@"content.height: %f", size.height); // NSLog(@"bounds.height: %f", bounds.size.height); // NSLog(@"inset.top: %f", inset.top); // NSLog(@"inset.bottom: %f", inset.bottom); // NSLog(@"pos: %f of %f", y, h); float reload_distance = 10; if(y > h + reload_distance) { NSLog(@"load more rows"); } }
reload_distance是指在table view滑到最底,且當使用者再滑動table view到某個值之後,
才開始load下一段資料,一樣需要一個bool來判斷是否需要load下一段資料。