首页 > 解决方案 > 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 数组。

我该怎么做呢?

标签: iosswiftswiftui

解决方案


SwiftUI ForEach语句View为每个Elementa返回 a Array。对于您的代码,您只需要运行一个VoidArray<Exercise>.append(newElement: Exercise)而不是获取多个View',因此您可以使用for循环map、 或Array.forEach(body: (_) throws -> Void).

如果附加的顺序newExercises很重要,最优雅的解决方案是将每个映射NewExercisefinalExercisesa 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")
        }
    }
}

推荐阅读