ios - 递归而不调用以前的函数

标签 ios swift algorithm recursion uicollectionview

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

要自动滚动的 Collection View 嵌套在第一个表格 View 单元格中。

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

这是我的代码:

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)

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

最佳答案

我相信你正在尝试做的是:

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 永远不会被释放。如果多个单元运行这个,那么它肯定会导致他们打架的问题。我希望它直接在 Collection View 上运行,而不是在单元格上运行。

关于ios - 递归而不调用以前的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54812450/

相关文章:

ios - 使用 Magical Record 添加到创建的实体属性

iOS Swift 组合 : cancel a Set<AnyCancellable>

ios - swiftui 3 View 栈布局,中间栈占空间

ios - 如何将两个 iOS 应用程序捆绑到一个 ipa 文件中

使用 UIImagePickerController/ImagePicker 的 iOS Swift 和 Xamarin 应用程序崩溃

ios - 如何将坐标从 didUpdateLocation 传送到某个 View Controller ?

javascript - 在 Javascript 中对具有特定异常的对象数组进行排序

algorithm - 在最佳时间计算一个数的阶乘

c# - “Grokkable”算法,用于理解指数为 float 的求幂

swift - 如何使用发布主题来观察变量的值?