我遇到一个问题,即我在详细信息视图中切换设置,并且在切换设置后,导航立即弹出回到主屏幕。这仅在使用ScrollView而不是主屏幕上的List时发生。有没有人有解决方案或知道是否可以解决此错误?我今天等待Xcode 11 Beta 7,但是并不能解决问题。
使用ScrollView的当前行为:
带有ScrollView的预期行为(带有列表的当前行为):
单击后退按钮可返回到主屏幕
import SwiftUI
import Combine
struct Sport: Identifiable{
var id = UUID()
var name : String
var isFavorite = false
var school : String
}
final class UserData: ObservableObject {
@Published var sportsData =
[
Sport(name: "soccer", isFavorite: false, school: "WPI"),
Sport(name: "tennis", isFavorite: true, school: "WPI"),
Sport(name: "swimming", isFavorite: true, school: "WPI"),
Sport(name: "running", isFavorite: true, school: "RIT"),
]
}
struct ContentView: View {
@EnvironmentObject var userData: UserData
var body: some View {
NavigationView{
List{
ForEach(userData.sportsData){ sport in
if sport.isFavorite{
NavigationLink(destination:
DetailsView(sport: sport)
){
HStack {
Text(sport.name)
Spacer()
Image(systemName: "star.fill")
.foregroundColor(sport.isFavorite ? .yellow : .gray)
}
}
}
}
}
}.navigationBarTitle("Settings")
}
}
struct DetailsView: View {
@EnvironmentObject var userData: UserData
var sport: Sport
var sportIndex: Int {
userData.sportsData.firstIndex(where: { $0.id == sport.id })!
}
var body: some View {
ZStack {
Text(sport.name).offset(x: 0, y: 100)
Button(action: {
self.userData.sportsData[self.sportIndex].isFavorite.toggle()
print(self.sport.isFavorite)
}) {
Image(systemName: "star.fill")
.foregroundColor(self.userData.sportsData[self.sportIndex].isFavorite ? .yellow : .gray)
}
}.padding(.horizontal)
}
}
#if DEBUG
struct Testing_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(UserData())
}
}
#endif
答案 0 :(得分:1)
可能会影响这一点的一件事是,如果 favorite == false
,您似乎正在破坏 forEach 中的原始 NavigationLink。
因此,如果那是我们进入 Detail 的 NavigationLink,那么当 favorite 设置为 false 时它就会消失。这是你打算做的吗?