首页 > 解决方案 > 递归而不调用先前的函数

问题描述

如何创建一个递归函数,一旦调用将只执行当前调用的具有下一个索引的函数?

要自动滚动的集合视图嵌套在第一个表格视图单元格中。

我一直在尝试创建一个可以作为常规循环工作的递归函数。不能使用循环,因为它在后台线程上运行。

这是我的代码:

var indexItem = 1

func autoScroll(time: Int) {
    DispatchQueue.main.async {
        self.run(after: time) {
            cell._collectionView.scrollToItem(
                at: IndexPath(row: indexItem, section: 0),
                at: .centeredHorizontally, animated: true
            )
            indexItem += 1
            autoScroll(time: 3)
            return
        }
    }
}

autoScroll(time: 3)

问题是它总是先调用具有前一个索引的函数,然后执行具有实际索引的函数。

标签: iosswiftalgorithmrecursionuicollectionview

解决方案


我相信你想要做的是:

func autoScroll(time: DispatchTimeInterval, indexItem: Int = 1) {
    DispatchQueue.main.asyncAfter(deadline: .now() + time) {
        cell._collectionView.scrollToItem(at: IndexPath(row: indexItem, section: 0), at: .centeredHorizontally, animated: true)
        autoScroll(time: time, indexItem: indexItem + 1)
    }
}

autoScroll(time: .seconds(3))

只需将值传递给函数。

不过,您确实需要一些标志来阻止这种情况。正如所写,这是确保cell永远不会被释放。如果多个单元运行此程序,那么它们肯定会引起问题。我希望它直接在集合视图上而不是在单元格上运行。


推荐阅读