Issue
This Content is from Stack Overflow. Question asked by Tometoyou
I have a view that should scale in and out, starting immediately when the view is shown and repeating forever. However, I find that it’s actually animating up and down as well as scaling much like in this post when it’s pushed from a navigation view:
struct PlaceholderView: View {
@State private var isAnimating = false
var body: some View {
Circle()
.background(Circle())
.frame(width: 30, height: 30)
.scaleEffect(self.isAnimating ? 0.8 : 1)
.animation(Animation.easeInOut(duration: 1).repeatForever())
.onAppear {
self.isAnimating = true
}
.frame(width: 50, height: 50)
.contentShape(
Rectangle()
)
}
}
struct SettingsView: View {
@State private var showPlaceholder = false
var body: some View {
NavigationView {
ZStack {
Button(
action: {
showPlaceholder = true
}, label: {
Text("Go to placeholder")
}
)
NavigationLink(
destination: PlaceholderView(),
isActive: $showPlaceholder
) {
EmptyView()
}
.hidden()
}
}
.navigationViewStyle(.stack)
}
}
Why is this and how can I stop this from happening?
Solution
The way that Animation works in general in iOS or macOS is: that it see and observe the deference in parameters and try to answer them, unless we say ignore some change! or just observe special change like I did in code!
import SwiftUI
struct ContentView: View {
@State private var toggleAnimation: Bool = Bool()
var body: some View {
VStack{
Text("Hi")
.background(Color.red)
.cornerRadius(2.0)
.scaleEffect(toggleAnimation ? 2.0 : 1.0)
.animation(toggleAnimation ? Animation.easeInOut(duration: 1).repeatForever(autoreverses: true) : Animation.easeInOut, value: toggleAnimation)
Button("Toggle Animation") { toggleAnimation.toggle() }
}
.frame(width:200, height:200)
.background(Color.black)
}
}
This Question was asked in StackOverflow by Clifton Labrum and Answered by ios coder It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.