当NSCollectionView滚动到内容结尾时加载更多数据(macOS)

时间:2018-01-03 19:22:30

标签: swift macos scroll nsscrollview nscollectionview

在我的macOS应用程序中,我有一个NSCollectionView。我下载了数据并将其放在集合视图中,现在我想在用户滚动到可用内容的底部时加载更多数据。在iOS上,我可以使用UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:)执行类似的操作,但我不确定如何在macOS上执行此操作。

当用户滚动到视图底部时,如何触发加载?

3 个答案:

答案 0 :(得分:0)

我在iOS上使用的一种可能方法是在显示特定项目时触发加载。在macOS上,可以使用collectionView(_:willDisplay:forRepresentedObjectAt) NSCollectionViewDelegate方法完成此操作。像这样:

func collectionView(_ collectionView: NSCollectionView, willDisplay item: NSCollectionViewItem, forRepresentedObjectAt indexPath: IndexPath) {
    if indexPath == self.lastIndexPath {
        loadNextSection()
    }
}

func loadNextSection() {
    guard let self.loading == false else {
        return
    }
    self.loading = true
    self.loader.loadSection(nextSection) { objects in
        self.nextSection += 1
        self.sections.append(objects)
        self.lastIndexPath = IndexPath(indexes: [self.sections.count, objects.count])
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
    }
}

答案 1 :(得分:0)

看起来,我解决了。创建观察。并连接nscollectionview的scrollview并在滚动时使用它:..

if (self.scrollViewColl.verticalScroller?.floatValue.isEqual(to: 1.0))! && loading == false

答案 2 :(得分:0)

或者,您可以检查indexPath.item是否等于data source array count,如果是,则调用加载数据源数组中数据的方法。

func collectionView(_ collectionView: NSCollectionView, willDisplay item: NSCollectionViewItem, forRepresentedObjectAt indexPath: IndexPath) {
    if indexPath.item == self.data_source_array.count-1 {
       self.method_to_load_more_data()
    }
}

添加更多数据后,请不要忘记reloadData()集合视图。