[英]How to animate a number that in wrapped in a View with SwiftUI?
Let say i have a simple view, and a number INSIDE another view:假设我有一个简单的视图,另一个视图中有一个数字:
struct ContentView: View {
@State private var counter = 0
var body: some View {
VStack {
Button(action: { self.counter += 1 }) {
Text("Add 1")
}
NumberView(currentValue: counter)
}
}
}
struct NumberView: View {
var currentValue: Int
var body: some View {
VStack {
Text("I don't want to be animated")
Text(currentValue.description)
.font(.largeTitle)
.foregroundColor(Color.black)
.padding(.all)
}
}
}
For every click I want the number to scale up for a second and go back as normal.对于每一次点击,我希望数字放大一秒钟,go 恢复正常。 (Using scale effect).
(使用比例效应)。 How can i animate this scaling for a second?
我怎样才能让这个缩放动画一秒钟?
try this:尝试这个:
struct ContentView: View {
@State private var counter = 0
@State var scale = false
var body: some View {
VStack {
Button(action: {
self.counter += 1
withAnimation(Animation.easeInOut(duration: 0.5)) {
self.scale.toggle()
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { (timer) in
withAnimation(Animation.easeInOut(duration: 0.5)) {
self.scale.toggle()
}
}
}
}) {
Text("Add 1")
}
NumberView(currentValue: counter)
.scaleEffect(scale ? 1.5 : 1)
}
}
}
struct NumberView: View {
var currentValue: Int
var body: some View {
Text(currentValue.description)
.font(.largeTitle)
.foregroundColor(Color.black)
.padding(.all)
}
}
ok, here the new answer for your changed requirement好的,这是您更改要求的新答案
struct ContentView: View {
@State private var counter = 0
@State var scale : CGFloat = 1
var body: some View {
VStack {
Button(action: {
self.counter += 1
withAnimation(Animation.easeInOut(duration: 0.5)) {
self.scale = 1.5
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { (timer) in
withAnimation(Animation.easeInOut(duration: 0.5)) {
self.scale = 1
}
}
}
}) {
Text ("add")
}
NumberView(currentValue: counter, scale: self.scale)
}
}
}
struct NumberView: View {
var currentValue: Int
var scale : CGFloat
var body: some View {
VStack {
Text("I don't want to be animated")
Text(currentValue.description)
.font(.largeTitle)
.foregroundColor(Color.black)
.padding(.all)
.scaleEffect(self.scale)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.