如何创建一个递归函数,一旦被调用将只执行具有下一个索引的当前调用函数?
要自动滚动的 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/