Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach loop not updating in real time

I'm using a ForEach to loop through an array of saved user input and display those, which displays everything correctly, unless I add a new input to this array, then the new item isn't displayed unless I navigate to another View then come back.

I've tried everything, from changing .id with .self, but nothing works.

Any idea guys? Thank you!

EDIT: It looks like it's my sheet that prevents my view from updating, I've tried simply adding the sheet code in my view and now the ForEach updates in real time, is there something I'm missing regarding how sheets could get in the way?

struct AnswersView: View {
@EnvironmentObject var vm: BrainstormViewModel
@Environment(\.presentationMode) var presentationMode
@State var mBIndex: Int
@State var substitute: [String] = []
@State var showSheet: Bool = false
@State var updater: Bool = false
var body: some View {
    ScrollView {
        VStack(alignment: .leading) {
            Text("How could I...")
            Text(vm.brainstormArray[mBIndex].title)
                .font(.system(size: 32, weight: .bold, design: .rounded))
                .multilineTextAlignment(.leading)
            Button {
                showSheet.toggle()
            } label: {
                ButtonSubview(icon: "play.fill", text: "Continue brainstorm")
                    .environmentObject(BrainstormViewModel())
            }

            ForEach(vm.brainstormArray[mBIndex].answersArray, id: \.self) { index in

                Text(index.name)
                    .font(.system(size: 20, weight: .bold, design: .rounded))
                    .padding(.top, 30)
                HStack {
                    Text(index.answer[0])

                        .padding()

                    Spacer()
                }

                .background(Color.MyTheme.orangeLight)
                .cornerRadius(16)
            }
        }

        .fullScreenCover(isPresented: $showSheet) {
            BrainstormView(mBIndex: mBIndex)
        }

        .navigationBarTitleDisplayMode(.inline)
    }
    .frame(maxWidth: .infinity)
    .padding()
    .background(Color.white)
}

}

like image 286
Charlie Maréchal Avatar asked Oct 25 '25 12:10

Charlie Maréchal


1 Answers

wherever you change the data, insert:

vm.objectWillChange.send()
like image 136
ChrisR Avatar answered Oct 27 '25 01:10

ChrisR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!