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
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