'Loading Animation is falling from top
im using this example to build a loading animation, and animated part is just falling from the sky.
struct ContentView: View {
@State private var isLoading = false
var body: some View {
ZStack {
Text("Loading")
.font(.system(.body, design: .rounded))
.bold()
.offset(x: 0, y: -25)
RoundedRectangle(cornerRadius: 3)
.stroke(Color(.systemGray5), lineWidth: 3)
.frame(width: 250, height: 3)
RoundedRectangle(cornerRadius: 3)
.stroke(Color.green, lineWidth: 3)
.frame(width: 30, height: 3)
.offset(x: isLoading ? 110 : -110, y: 0)
.animation(Animation.linear(duration: 1).repeatForever(autoreverses: false))
}
.onAppear() {
self.isLoading = true
}
}
}
Solution 1:[1]
You have a couple of problems with your code. First, .animation() has been deprecated because it is unreliable. You should be using .animation(_:value:) instead.
While I can't duplicate the "falling from the top" problem, I think I know what it is. It is an animation timing issue when the animation is triggered before the view is on screen. If you continue to get this, wrap your change in .onAppear() in DispatchQueue.main.asyncAfter(deadline:). The code with this is below:
struct ContentView: View {
@State private var isLoading = false
var body: some View {
ZStack {
Text("Loading")
.font(.system(.body, design: .rounded))
.bold()
.offset(x: 0, y: -25)
RoundedRectangle(cornerRadius: 3)
.stroke(Color(.systemGray5), lineWidth: 3)
.frame(width: 250, height: 3)
RoundedRectangle(cornerRadius: 3)
.stroke(Color.green, lineWidth: 3)
.frame(width: 30, height: 3)
.offset(x: isLoading ? 110 : -110, y: 0)
// Use this init for .animation, as the other one is depracated
.animation(Animation.linear(duration: 1).repeatForever(autoreverses: false), value: isLoading)
}
.onAppear() {
// This may not be necessary, but if you get the "falling from the top" problem, put this
// around isLoading = true
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
isLoading = true
}
}
}
}
Solution 2:[2]
Can you try 3 things:
- Remove the instances of offset coordinates where value = 0. Like
x=0y=0etc - Add stop animation inside onDisappear()
.onDisappear() {
self.isLoading = false
}
- If you are using
.transition()in this or any of its parent view, try removing that
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yrb |
| Solution 2 | Suyash Medhavi |
