I am new to SwiftUI. I am trying to update an array of mockFlights (in this case as a dummy test just at index 0 for departureAirportIata:) with a string from the TextField. The data are displayed from the array as they should and when using button "Submit" with print statements, the viewModel.flights gets updated but the view never changes.
I have a model with mockData:
import Foundation
struct Flight: Identifiable, Equatable {
let id = UUID()
var departureAirportIata : String
var arrivalAirportIata : String
var departureAirportIcao : String
var arrivalAirportIcao : String
var numberOfDayLandings : Int
var numberOfNightLandings : Int
var aircraftType : String
var aircraftRegistration : String
var picName : String
var sicName : String
var remark : String?
}
struct MockData {
static var mockFlights = [
Flight(departureAirportIata: "WRO", arrivalAirportIata: "PRG", departureAirportIcao: "EPWR", arrivalAirportIcao: "LKPR", numberOfDayLandings: 2, numberOfNightLandings: 0, aircraftType: "B738", aircraftRegistration: "OK-UTH", picName: "SELF", sicName: "EVA"),
Flight(departureAirportIata: "LGW", arrivalAirportIata: "OSL", departureAirportIcao: "EGKK", arrivalAirportIcao: "ENGM", numberOfDayLandings: 1, numberOfNightLandings: 0, aircraftType: "B738", aircraftRegistration: "OK-ILS", picName: "SELF", sicName: "PETR", remark: "DLY: 81, CTOT 1950"),
]
}
ViewModel with the following code:
import SwiftUI
class FlightVM : ObservableObject {
@Published var flights : [Flight]
init() {
let flights = MockData.mockFlights
self.flights = flights
}
}
Parent view:
import SwiftUI
struct FlightsOverView: View {
@StateObject var viewModel: FlightVM
var body: some View {
NavigationStack {
List(viewModel.flights, id: \.id) { flight in
NavigationLink(
destination: FlightDetailView(flight: flight), label: {
FlightCell(flight: flight)
.listRowInsets(EdgeInsets(top: 5, leading: 8, bottom: 5, trailing: 8))
})
}
.listStyle(PlainListStyle())
.navigationTitle("Flights")
}
}
}
And childview:
import SwiftUI
struct FlightDetailView: View {
@State var flight : Flight
@StateObject var viewModel = FlightVM()
var body: some View {
NavigationView{
Form {
Section(header: Text("Flight Info")){
Text(flight.aircraftRegistration)
Text(flight.aircraftType)
Text(flight.arrivalAirportIata)
Text(flight.departureAirportIata)
TextField("Departure airport", text: $flight.departureAirportIata)
}
Button("Submit", action: {
viewModel.flights[0] = flight
print(viewModel.flights)
print(flight)
})
}
}
}
}
The data are displayed from the array as they should and when using button "Submit" with print statements, the viewModel.flights gets updated but the view never changes.