Search code examples
swiftswiftuiobservedobject

Sheet contents won't update depending on parameters


I am calling a sheet when a button is pressed. The button is generated through a ForEach loop and I want to pass the current object into the new sheet. Depending on this object I want the sheet to display different variables.

ForEach(processor.matchEvents){event in
    Button(action: {showSheet.toggle()}) {
        ZStack{
            RoundedRectangle(cornerRadius: 15)
             .fill(event.team.teamColor)
             .frame(minWidth: 150, maxHeight: .infinity)
             .padding([.vertical], 10)
             .padding([.horizontal], 5)
                                
            VStack(alignment: .center, spacing: 5){
                Group{
                    Text(event.team.teamName)
                    Text(event.time)
                    Text(event.event)
                }
                                
            }
        }
    }
     .sheet(isPresented: $showSheet){
         EditEventView(team: event.team, event: event)
    }
}

I have stripped out most styling to help shorten the code. Below is the code I am trying to run in the sheet, but am not getting the new updated event

struct EditEventView: View {
    @ObservedObject var team: Team
    var event: MatchEvent
    
    @Environment(\.presentationMode) var presentationMode
    
    @State private var playerSelect = 0
    
    @ObservedObject var processor = EventsProcessor.shared
    
    var body: some View{

        NavigationView{
            Form{
                Section(header: Text("Event")){
                    Text(team.teamName)
                    Text(event.event)
                    Text(event.player)
                    Text(event.time)

                }
            }
        }
    }
}

Each of the events are stored inside another bit of code, linked below. This is so they are accessible around the entire program.

struct MatchEvent: Identifiable{
    var id = UUID()
    
    var team: Team
    
    var time: String
    var event: String
    var player: String
}

class EventsProcessor: ObservableObject {
    static let shared = EventsProcessor()
    
    @Published var matchEvents = [MatchEvent]()
    
    func addEvent(time: String, event: String, player: String, team: Team){
        matchEvents.append(MatchEvent(team: team, time: time, event: event, player: player))
    }

}

I have got the sheets to display and that bit is working, however it will constantly display the same data and not update whenever I go to a new event. Any help would be appreciated.


Solution

  • You already did it the right way with @ObservedObject var team: Team

    Simply change var event: MatchEvent to @ObservedObject var event: MatchEvent.

    The @ObservedObject Property Wrapper comes from Combine and is "looking for Updates and updating the View once an Update was found".