I'm trying to achieve a smooth transition between 2 states of a SwiftUI view. The following code works great, when the offset changes, SwiftUI interpret that as 2 states of the same view (same identity), and transition with a slide of the view.
import SwiftUI
struct AnimationView: View {
@State var number: Int = 0
var body: some View {
VStack {
// VIEW #1
Image(systemName: "0.circle.fill")
// VIEW #2
// Image(systemName: "\(self.number).circle.fill")
.id("my-view-identity")
.offset(x: self.number%2==0 ? 50 : -50, y: 0)
Button {
self.number += 1
} label: {
Text("Add 1")
}
}
.animation(.linear(duration: 1), value: self.number)
}
}
struct AnimationView_Previews: PreviewProvider {
static var previews: some View {
AnimationView()
}
}
The problem is when I try using the VIEW #2, SwiftUI doesn't interpret the 2 states Image(systemName: "0.circle.fill")
and Image(systemName: "1.circle.fill")
as 2 states of the same view, but rather 2 different views with different identity, even tho I manually set an id. This results in a fade out of the first view, and a fade in of the second.
I also tried using a subview to create some kind of view proxy and set the fixed id to that view, but that's not doing anything.
I've watch the WWDC21 talk Demystify SwiftUI and think I have a good grasp over view identity, but this one I can't figure, my guess is that we can manually set a different id for a single view, but we can't do the opposite: set the same id for different views. Am I right ? Is there any trick that would make it possible ?