Here's a basic example of what doesn't work:
import SwiftUI
struct Test : View {
@State var swapped = false
var body: some View {
if swapped { Color.green }
Color.blue.tapAction {
withAnimation { self.swapped.toggle() }
}
if !swapped { Color.green }
}
}
SwiftUI has no way to figure out that I think of the first Color.green
and the second Color.green
as the same view, so of course the animation just fades one of them out while fading the other one in at the new location. I'm looking for the way to indicate to SwiftUI that these are the same view, and to animate it to the new location. I discovered the .id()
modifier with great excitement because I believed that it would give me the effect that I want:
import SwiftUI
struct Test : View {
@State var swapped = false
var body: some View {
if swapped { Color.green.id("green") }
Color.blue.tapAction {
withAnimation { self.swapped.toggle() }
}
if !swapped { Color.green.id("green") }
}
}
This, unfortunately, does not work either. I'm unbelievably excited about SwiftUI, but it seems to me that the ability to change the structure of the view hierarchy while preserving view identity is quite important. The actual use case which prompted me to think about this is that I have a handful of views which I'm trying to create a fan animation for. The simplest way would be to have the items in a ZStack
in one state so that they are all on top of each other, and then to have them in a VStack
in the fanned out state, so that they're vertically spread out and all visible. Changing from a ZStack
to a VStack
of course counts as a change to the structure and therefore all continuity between the states is lost and everything just cross fades. Does anyone know what to do about this?