我有一个视图,可以调用 API 来提取附近的餐厅数据并将其显示在列表中。我在该视图的导航栏中放置了一个按钮,以显示最终将显示用户过滤器选项的工作表。目前,它使用放置在表单中的 Picker 来允许用户选择他们想要的结果排序方式。我在过滤器视图中使用带有 @Binding 属性包装器的变量将所选值传递给餐厅数据视图 (selectedOption) 中的 @State 变量。在重新加载视图之前,一切都很好。通过转到不同的视图或重新启动应用程序。在我的 API 调用中,餐厅数据视图的 onAppear 函数中的 selectedOption 变量似乎被重置为我在定义 @State 变量时设置的默认值。我想知道是否有办法通过餐厅数据视图的视图重新加载来保留过滤器视图中选择的值。
餐厅数据视图:
import SwiftUI
import SwiftyJSON
import SDWebImageSwiftUI
struct RestaurantsView: View {
@EnvironmentObject var locationViewModel: LocationViewModel
@EnvironmentObject var venueDataViewModel: VenueDataViewModel
@State var selectedOption: String = "rating"
@State private var showingSheet = false
@State private var searchText = ""
@State private var showCancelButton: Bool = false
var body: some View {
let CPLatitude: Double = locationViewModel.lastSeenLocation?.coordinate.latitude ?? 0.00
let CPLongitude: Double = locationViewModel.lastSeenLocation?.coordinate.longitude ?? 0.00
GeometryReader { geometry in
VStack {
Text("Restaurants")
.padding()
List(venueDataViewModel.venuesListTen) { index in
NavigationLink(destination: RestaurantsDetailView(venue: index)) {
HStack {
VStack(alignment: .leading,spacing: 6) {
Text(index.name ?? "")
.font(.body)
.lineLimit(2)
Text(index.address ?? "")
.font(.subheadline)
.lineLimit(2)
}
}
}
Spacer()
if index.image != nil {
WebImage(url: URL(string: index.image ?? ""),options: .highPriority,context: nil)
.resizable()
.frame(width: 70,height: 70,alignment: .center)
.aspectRatio(contentMode: .fill)
.cornerRadius(12)
}
}
Text("Selected: \(selectedOption)")
Spacer()
}.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
showingSheet.toggle()
},label: {
Image(systemName: "line.horizontal.3")
.imageScale(.large)
}
)
.sheet(isPresented: $showingSheet,content: {
NavigationView {
RestaurantsFilterView(selectedOption: self.$selectedOption)
}
})
}
}
.onAppear {
venueDataViewModel.retrieveVenues(latitude: CPLatitude,longitude: CPLongitude,category: "restaurants",limit: 50,sortBy: selectedOption,locale: "en_US") { (response,error) in
if let error = error {
print("\(error)")
}
}
}
}
}
}
过滤视图:
import SwiftUI
struct RestaurantsFilterView: View {
@EnvironmentObject var locationViewModel: LocationViewModel
@EnvironmentObject var venueDataViewModel: VenueDataViewModel
var sortOptions = ["rating","review_count"]
@Binding var selectedOption: String
var body: some View {
let CPLatitude: Double = locationViewModel.lastSeenLocation?.coordinate.latitude ?? 0.00
let CPLongitude: Double = locationViewModel.lastSeenLocation?.coordinate.longitude ?? 0.00
VStack {
Text("Filter")
Form {
Section {
Picker(selection: $selectedOption,label: Text("Sort")) {
ForEach(sortOptions,id: \.self) {
Text($0)
}
}.onChange(of: selectedOption) { Equatable in
venueDataViewModel.retrieveVenues(latitude: CPLatitude,error) in
if let error = error {
print("\(error)")
}
}
}
}
}
}
}
}
我还是 Swift 和 SwiftUI 的新手,所以我很感谢您的帮助。 谢谢!