我正在使用此答案NavigationButton
中的自定义,以便在从列表导航到新视图时能够加载特定视图的数据。它工作得很好,但问题是当我尝试在 ForEach 循环中使用它时,我最终会得到带有多个变量的多个导航链接,这些变量都被告知要推送一个新视图,这会导致 SwiftUI 然后导航到新视图自动返回父视图(错误)。如何在不触发错误的情况下保留在导航到新视图时能够触发代码运行的功能。isActive
@State
ForEach(workouts) { workout in
NavigationButton(
action: {
//load data for Destination
},
destination: {
WorkoutDetailView().environmentObject(dataStore)
},
workoutRow: { WorkoutRow(trackerWorkout: workout) }
)
}
struct NavigationButton<Destination: View, WorkoutRow: View>: View {
var action: () -> Void = { }
var destination: () -> Destination
var workoutRow: () -> WorkoutRow
@State private var isActive: Bool = false
var body: some View {
Button(action: {
self.action()
self.isActive.toggle()
}) {
workoutRow()
.background(
ScrollView { // Fixes a bug where the navigation bar may become hidden on the pushed view
NavigationLink(destination: LazyDestination { self.destination() },
isActive: self.$isActive) { EmptyView() }
}
)
}
}
}
// This view lets us avoid instantiating our Destination before it has been pushed.
struct LazyDestination<Destination: View>: View {
var destination: () -> Destination
var body: some View {
self.destination()
}
}