[英]SwiftUI - Involuntary navigation between views
我有兩種看法:
父視圖首先解碼捆綁的 JSON 文件,然后將 object 傳遞給子視圖。 然后子視圖將 object(加上幾個附加對象)保存到 Core Data。
那部分工作正常。 問題是保存到核心數據后,子視圖然后導航回父視圖,我不知道為什么。 預期行為是導航回根視圖。
父視圖:
struct SelectCityView: View {
@State private var cities = [Destination]()
@State private var searchText: String = ""
var body: some View {
VStack {
SearchBar(text: $searchText)
List {
// Filter decoded array by search text
ForEach(cities.filter{self.searchFor($0.city)}.sorted(by: { $0.city < $1.city })) { destination in
// Here's where the parent view passes the object to the child view
NavigationLink(destination: SelectTravelDatesView(selectedCity: destination)) {
Text("\(destination.city), \(destination.country)")
}
}
}.id(UUID())
}.navigationTitle("Select city")
.onAppear(perform: {
// Decode JSON data from bundle
cities = Bundle.main.decode([Destination].self, from: "cities.json")
})
}
private func searchFor(_ searchQuery: String) -> Bool {
return (searchQuery.lowercased(with: .current).hasPrefix(searchText.lowercased(with: .current)) || searchText.isEmpty)
}
}
子視圖:
struct SelectTravelDatesView: View {
@Environment(\.managedObjectContext) private var viewContext
@State var selectedCity: Destination?
@State private var startDate = Date()
@State private var endDate = Date()
var body: some View {
Form {
Section(header: Text("Trip start date")) {
DatePicker(selection: $startDate, in: Date()..., displayedComponents: .date) {
Text("Trip start date")
}.datePickerStyle(GraphicalDatePickerStyle())
}
Section(header: Text("Trip end date")) {
DatePicker(selection: $endDate, in: startDate..., displayedComponents: .date) {
Text("Trip start date")
}.datePickerStyle(GraphicalDatePickerStyle())
}
}.navigationTitle("Select dates")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
// Save to Core Data
Button(action: {
addItem()
}, label: {
Text("Save")
})
}
}
}
private func addItem() {
withAnimation {
let newItem = Trip(context: viewContext)
if let destination = selectedCity {
newItem.timestamp = Date()
newItem.destination = destination.city
newItem.startDate = startDate
newItem.endDate = endDate
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
}
任何幫助將不勝感激。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.