I\'m attempting to construct an animation using SwiftUI.
Start: [ A ][ B ][ D ]
End: [ A ][ B ][ C ][ D ]
The key elements of the anima
It's hard to tell what exactly you're going for or what's not working. It would be easier to help you if you showed the "wrong" animation you came up with or shared your code.
Anyway, here's a take. I think it sort of does what you specified, though it's certainly not perfect:
Observations:
The animation relies on the assumptions that (A) and (B) together are wider than (C). Otherwise, parts of (C) would appear to the left of A at the start of the animation.
Similarly, the animation relies on the fact that there's no spacing between the views. Otherwise, (C) would be appear to the left of (B) when it's wider than (B).
It may be possible to solve both problems by placing an opaque underlay view in the hierarchy such that it is below (A), (B), and (D), but above (C). But I haven't thought this through.
The HStack
seems to expand a tad more quickly than (C) is sliding in, which is why a white portion appears briefly. I didn't manage to eliminate this. I tried adding the same animation(.basic())
modifier to the HStack
, the transition, the withAnimation
call, and the VStack
, but that didn't help.
The code:
import SwiftUI
struct ContentView: View {
@State var thirdViewIsVisible: Bool = false
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack(spacing: 0) {
Text("Lorem ").background(Color.yellow)
.zIndex(1)
Text("ipsum ").background(Color.red)
.zIndex(1)
if thirdViewIsVisible {
Text("dolor sit ").background(Color.green)
.zIndex(0)
.transition(.move(edge: .leading))
}
Text("amet.").background(Color.blue)
.zIndex(1)
}
.border(Color.red, width: 1)
Button(action: { withAnimation { self.thirdViewIsVisible.toggle() } }) {
Text("Animate \(thirdViewIsVisible ? "out" : "in")")
}
}
.padding()
.border(Color.green, width: 1)
}
}