SwiftUI, using ForEach inside ZStack causes screen flickering

804 Views Asked by At
  • when calling router1(), there is quick (white screen) flickering
  • when calling router2(), no flickering

NOTE: in both cases navigationLevelsStack just has 1 element

It seems it just depends on the fact that router1() uses a ForEach?

Is there a way to make ForEach not causing that flickering?

@ViewBuilder func router1(_ stateProvider: StateProvider,_ events: Events) -> some View {

    ZStack {
        ForEach(navigationLevelsStack, id: \.self.URI) { screenIdentifier in
             self.screenPicker(screenIdentifier)
        }
    }

}

@ViewBuilder func router2(_ stateProvider: StateProvider,_ events: Events) -> some View {

    ZStack {
             self.screenPicker(navigationLevelsStack.last!)
        }
    }

}
1

There are 1 best solutions below

1
On

I found the reason:

It is because self.URI is a computed property, so each time it was called, it took time to process.

UPDATE:

Actually the reason is not because .URI is a computed property. It has to do with the fact that the old ForEach id value is replaced by a new ForEach id value. If you want to avoid the flickering, it's ok to render a different view, but the ForEach id should stay the same. So, it makes sense it to be an index number.