ios - 递归而不调用先前的函数
问题描述
如何创建一个递归函数,一旦调用将只执行当前调用的具有下一个索引的函数?
要自动滚动的集合视图嵌套在第一个表格视图单元格中。
我一直在尝试创建一个可以作为常规循环工作的递归函数。不能使用循环,因为它在后台线程上运行。
这是我的代码:
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
永远不会被释放。如果多个单元运行此程序,那么它们肯定会引起问题。我希望它直接在集合视图上而不是在单元格上运行。
推荐阅读
- spring-boot-admin - Eureka 服务 UP,SBA DOWN
- mysql - 如何在 MySQL 中检查一个 SELECT 的结果是否包含另一个 SELECT?
- python - 根据时间序列将大熊猫数据框拆分为较小的数据框
- java - 是否可以在 java 应用程序中使用 jQAssistant 作为工具?
- reactjs - 当单个组件更新时,为什么所有组件都会更新相同的值?
- cloud - 带有简单 wordpress 站点的 aws cloud front ssl
- sparql - SPARQL:找出用于链接的属性
- java - 如何使用反射抽象(减少)代码以获取字段(整数、长整数、浮点数、双精度)并进行一些计算?
- popup - 关闭一个模态窗口,页面跳转到顶部(不需要)
- php - 构造适当的查询:带有 child_of、depth 和 meta_query 的 WP_Term_Query