Updating a Scroll View with a global array

132 Views Asked by At

On my main screen I have a Scroll View which I want to display all of the events that are happening within the app. Currently I have this defined as a global variable as shown below:

struct matchEvent: Identifiable{
    var id = UUID()
    
    var time: String
    var event: String
    var player: String
}

var matchEvents = [matchEvent]()

func addEvent(time: String, event: String, player: String){
    matchEvents.append(matchEvent(time: time, event: event, player: player))
}

The function addEvent() is called from inside different methods of other classes around the app, hence why I made it global. How do I get the app to update the scroll view when the array matchEvents is updated? I have put my ScrollView code below.

struct eventList: View{
    var body: some View{
        ScrollView(.horizontal){
            HStack(matchEvents){
                ForEach(matchEvents){event in
                    Button(event.event){
                        print("Clicked")
                    }
                }
            }
        }
    }
}

Any help would be appreciated

1

There are 1 best solutions below

0
On BEST ANSWER

You can wrap matchEvents into class and use shared instance to update/observe it.

Here is possible approach. Tested with Xcode 12.1 / iOS 14.1

Note: capitalised types to follow convention

struct MatchEvent: Identifiable{
    var id = UUID()
    
    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){
        matchEvents.append(MatchEvent(time: time, event: event, player: player))
    }
}

struct EventListView: View{
    @ObservedObject var processor = EventsProcessor.shared
    
    var body: some View{
        ScrollView(.horizontal){
            HStack {
                ForEach(processor.matchEvents){event in
                    Button(event.event){
                        print("Clicked")
                    }
                }
            }
        }
    }
}