Swift 4 UICollectionView检测滚动结束

时间:2018-02-09 12:04:49

标签: ios swift xcode uicollectionview swift4

我的应用上有Horizontal UICollectionView,当用户在左侧拖动时到达UICollectionView的末尾(或接近末尾)时,我想加载更多数据。

我正在使用Swift 4.我找到了一些Swift 3解决方案,但它们对我不起作用。

我目前的代码是:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.videoViewModel.images.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
    cell.imgImage.image = self.videoViewModel.images[indexPath.row]

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    updateVideo(data: self.videoViewModel.relatedVideos[indexPath.row])
}

5 个答案:

答案 0 :(得分:7)

您可以使用集合视图的cellForItem或willDisplayItem方法。检查是否显示最后一个单元格,然后加载数据。 Forexample:

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row == dataSource.count - 1 ) { //it's your last cell
       //Load more data & reload your collection view

    }
}

答案 1 :(得分:4)

实施scrollViewDidScroll的方法UIScrollViewDelegate

var isLoading: Bool = false

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let contentOffsetX = scrollView.contentOffset.x
    if contentOffsetX >= (scrollView.contentSize.width - scrollView.bounds.width) - 20 /* Needed offset */ {
        guard !self.isLoading else { return }
        self.isLoading = true
        // load more data
        // than set self.isLoading to false when new data is loaded
    }
}

答案 2 :(得分:1)

为页码取一个bool变量和一个整数变量,如下所示:

var isDataLoading = false
var pageCount:Int = 1 // Pass this page number in your api

在cellForItemAt方法中添加以下代码:

if !isDataLoading && indexPath.row == videoViewModel.count - 1 {
            isDataLoading = true
            pageCount += 1
// add you api call code here with pageCount
        }

一旦从api中获取数据,请将isDataLoading bool设置为false,如下所示:

self.isDataLoading = false

答案 3 :(得分:1)

这是简单的登录名,它将下至上一个索引... !!!

func ScrollEnd() {
          let lastSectionIndex = (self.collectionView?.numberOfSections)! - 1
         let lastItemIndex = (self.collectionView.numberOfItems(inSection: lastSectionIndex)) - 1
           let index =  IndexPath(item: lastItemIndex, section: lastSectionIndex)
           if messages.count != 0{
               self.collectionView!.scrollToItem(at: index, at: UICollectionView.ScrollPosition.bottom, animated: false)
           }    }

答案 4 :(得分:0)

将此添加到您的collectionView willDisplayCell委托中

if (indexPath.row == dataSource.count - 1 ) {
 //it's your last cell

//Load more data & reload your collection view
  }