我有一个 CoordinateList 视图,它显示了已输入的 CoordinateRow 视图的列表,并且可以就地编辑(在列表视图中)。要将新点添加到列表中,用户按下列表底部的按钮,它会添加一行(无需转到另一个屏幕)。如何让它更新视图以显示这个新条目?我尝试用一个函数包装坐标列表的附加函数,以便在添加到列表时可以调用 objectWillChange.send() ,但它似乎没有做任何事情。
我想我没有足够的声誉来上传图片,但这是一张图片:
import SwiftUI
class LocationTime : ObservableObject {
@Published var lat: String = "0.0"
@Published var lon: String = "0.0"
@Published var timestamp: String = "SomeDateTime"
}
class ModelData: ObservableObject {
@Published var positionCoords = [LocationTime]()
func appendPosition(_ loc: LocationTime) {
objectWillChange.send()
positionCoords.append(loc)
}
}
struct CoordinateRow: View {
@EnvironmentObject var modelData: ModelData
var pointIndex : Int
var body: some View {
HStack {
Text("Lon: ")
TextField("40",text:$modelData.positionCoords[pointIndex].lon)
Text("Lat: ")
TextField("",text:$modelData.positionCoords[pointIndex].lat)
Text("Time: ")
TextField("time",text:$modelData.positionCoords[pointIndex].timestamp)
}.padding()
.overlay(RoundedRectangle(cornerRadius:16)
.stroke(Color.blue,lineWidth:4.0))
}
}
struct CoordinateList: View {
@EnvironmentObject var modelData : ModelData
var body: some View {
VStack{
Text("Location Log")
.font(.largeTitle).padding()
List{
ForEach(modelData.positionCoords.indices){
CoordinateRow(pointIndex: $0).environmentObject(modelData)
}
}
Button(action:{
modelData.appendPosition(LocationTime())
print(modelData.positionCoords.count)
}){
Image(systemName: "plus.circle")
.imageScale(.large)
.scaleEffect(2.0)
.padding()
}
Spacer()
}
}
}