我正在尝试将字符串从数组传递到Text(),但是只能通过首先将其传递通过列表才能使它起作用吗?我已经尝试过class.struct.item或struct.item等的每种组合,请让我知道如何将其直接传递给Text()以便在其他视图中使用。
import SwiftUI
struct WorkoutView: View {
@EnvironmentObject var workoutElements: WorkoutElements
@State private var newWorkout = WorkoutElement(redWorkout: "")
var body: some View {
NavigationView {
List(workoutElements.workouts) { item in
VStack {
Text(item.redWorkout)
}
}
}
.onAppear {
// MARK: fetch from CloudKit
WorkoutFetcher.fetch { (result) in
switch result {
case .success(let newWorkout):
self.workoutElements.workouts.append(newWorkout)
print("succesfully fetched Item")
case .failure(let err):
print(err.localizedDescription)
}
}
}
}
}
struct WorkoutView_Previews: PreviewProvider {
static var previews: some View {
WorkoutView()
}
}
// this works for a list
//List(workoutElements.workouts) { item in
//VStack {
//Text(item.redWorkout)
//}
//}
// but this doesn't work for Text()
// Text(workoutElements.workouts.redworkouts)
// Text(workouts.redworkouts)
//etc
答案 0 :(得分:1)
如果您只想将它们结合在一起,可以如下所示(据我所知,您的模型)
Text("\(workoutElements.workouts.reduce("") { $0 + $1.redWorkout })")
如果需要任何分隔符,则只需替换为
$0 + $1.redWorkout + ". "