我需要将一些绑定传递给一个可写的表格。我想出了一个可行的方法,但似乎效率很低。
我重新创建了一个非常简化的代码版本,用作示例。
我有一个自定义的LocationStruct结构体...
struct LocationStruct {
var id = UUID()
var name: String
var location: CLLocationCoordinate2D?
var haveVisited = false
}
然后我有一个父视图,显示了一些LocationStruct
的信息 - 起点、途经点数组和终点...
struct ContentView: View {
@State var origin = LocationStruct(name: "Paris")
@State var waypoints = [LocationStruct(name: "Berlin"), LocationStruct(name: "Milan")]
@State var destination = LocationStruct(name: "Venice")
@State var selectedLocation: Int?
@State var showSheet = false
var body: some View {
VStack{
HStack{
Text("Origin:")
Spacer()
Text(origin.name)
}
.onTapGesture{
selectedLocation = 1000
showSheet = true
}
ForEach(waypoints.indices, id:\.self){ i in
HStack{
Text("Waypoint \(i + 1):")
Spacer()
Text(waypoints[i].name)
}
.onTapGesture{
selectedLocation = i
showSheet = true
}
}
HStack{
Text("Destination:")
Spacer()
Text(destination.name)
}
.onTapGesture{
selectedLocation = 2000
showSheet = true
}
}
.padding()
.sheet(isPresented: $showSheet){
LocationSheet(origin: $origin, waypoints: $waypoints, destination: $destination, selectedLocation: $selectedLocation)
}
}
}
我需要读写ContentView上被点击的位置对象。如果是起点或终点,我会将selectedLocation
值设置为1000或2000,否则它将被设置为航路点数组索引(航路点数量有限,因此不会超过1000)。
在很多地方我都不得不重复使用“if let selectedLocation = ...”。有没有更好的方法来做到这一点,也许是某种计算绑定或其他方法?
struct LocationSheet: View {
@Binding var origin: LocationStruct
@Binding var waypoints: [LocationStruct]
@Binding var destination: LocationStruct
@Binding var selectedLocation: Int?
var body: some View {
VStack{
if let selectedLocation = selectedLocation {
switch selectedLocation {
case 1000:
TextField("", text: $origin.name).textFieldStyle(.roundedBorder)
case 2000:
TextField("", text: $destination.name).textFieldStyle(.roundedBorder)
default:
TextField("", text: $waypoints[selectedLocation].name).textFieldStyle(.roundedBorder)
}
}
Button(action: { markAsVisted() }){
Text("Visited")
}
}
.padding()
}
func markAsVisted(){
if let selectedLocation = selectedLocation {
switch selectedLocation {
case 1000:
origin.haveVisited = true
case 2000:
destination.haveVisited = true
default:
waypoints[selectedLocation].haveVisited = true
}
}
}
}
提前致谢