ios - SwiftUI 中按钮操作内的 ForEach 循环?
问题描述
我知道 ForEach 循环通常用于显示视图。当我在操作按钮中放置一个 ForEach 循环时,它几乎告诉我按钮操作不符合视图协议。那么如何使用循环使按钮执行多个操作呢?
struct SomeView: View {
var newExercises = [NewExercise]()
var finalExercises = [Exercise]()
var body: some View {
Button(action: {
ForEach(newExercises) { newExercise in
//.getExercise() returns an Exercise object
finalExercises.append(newExercise.getExercise())
}
}) {
Text("Done")
}
}
}
我希望按钮为 newExercises 数组中的每个 newExercise 添加一个练习(通过调用 .getExercise())到 finalExercises 数组。
我该怎么做呢?
解决方案
新SwiftUI
ForEach
语句View
为每个Element
a返回 a Array
。对于您的代码,您只需要运行一个Void
,Array<Exercise>.append(newElement: Exercise)
而不是获取多个View
',因此您可以使用for
循环map
、 或Array.forEach(body: (_) throws -> Void)
.
如果附加的顺序newExercises
很重要,最优雅的解决方案是将每个映射NewExercise
到finalExercises
a Exercise
,并将结果附加到Array<Exercise>
, Array<Exercise>.append(contentsOf: Sequence)
。
struct SomeView: View {
@State var newExercises = [NewExercise]()
@State var finalExercises = [Exercise]()
var body: some View {
Button(action: {
self.finalExercises.append(contentsOf:
self.newExercises.map { newExercise -> Exercise in
newExercise.getExercise()
}
)
}) {
Text("Done")
}
}
}
如果附加的顺序newExercises
无关紧要,您可以调用Array<Exercise>.append(newElement: Exercise)
from newExcercises.forEach
,这与SwiftUI
ForEach
语句不同:
struct SomeView: View {
@State var newExercises = [NewExercise]()
@State var finalExercises = [Exercise]()
var body: some View {
Button(action: {
self.newExercises.forEach { newExercise in
self.finalExercises.append(newExercise.getExercise())
}
}) {
Text("Done")
}
}
}
使用 for 循环完成所需内容的方法很简单,但不太优雅:
struct SomeView: View {
@State var newExercises = [NewExercise]()
@State var finalExercises = [Exercise]()
var body: some View {
Button(action: {
for newExercise in self.newExercises {
self.finalExercises.append(newExercise.getExercise())
}
}) {
Text("Done")
}
}
}
推荐阅读
- c# - 检测用第一根手指按下按钮,但如果用更多手指按下则不检测 Unity
- node.js - 使用 npm start 时不断循环从云存储桶下载谷歌云存储文件
- amazon-web-services - 如何在 AWS EMR 上通过调度程序 http api (tcp/8081) 提交作业?
- internet-explorer - 问题:Polyfill.io 需要刷新页面才能工作
- pyspark - 如何将包含 numpy.ndarray 元素的 pandas 数据框转换为 pyspark 数据框?
- java - Spring-batch-admin-manager 1.3.1.RELEASE:java.lang.NoClassDefFoundError:org/codehaus/jackson/map/ObjectMapper
- haskell - 从语法生成随机项(简单类型的 lambda 演算)
- javascript - NodeJS:将响应缓冲区直接写入函数参数
- php - 使用来自父实体的生成值
- ios - 使用修复字符串生成 UUID 对象