1

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

2

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")
                    }
                }
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.