[英]Animation works the first time, but then
Trying to animate a SwiftUI
view.尝试为
SwiftUI
视图设置动画。 Works perfectly the first time, but then does nothing.第一次完美运行,但随后什么也不做。
self.pressed
starts out as false
. self.pressed
开始为false
。 I set it to true
and then I switch it back to false
.我将其设置为
true
,然后将其切换回false
。
I want to scale it up and then scale it back it down on button press.我想放大它,然后在按下按钮时将其缩小。
What am I missing here?我在这里缺少什么?
Button(action: {
withAnimation(.linear(duration: 3)) {
self.pressed = true
}
withAnimation(.linear(duration: 3)) {
self.pressed = false
}
}) {
Wedge(startAngle: .init(degrees: 270), endAngle: .init(degrees: 360))
.fill(Color.green)
.frame(width: 200, height: 200)
.offset(x: -100, y: 100)
.scaleEffect(self.pressed ? 1.2 : 1.0)
}
Basically it resizes my wedge shape when I press it, but then does nothing the next time I press it.基本上,当我按下它时它会调整我的楔形形状,但下次我按下它时什么也不做。
I did get it work with DispatchQueue
, but it seems like a hack:我确实让它与
DispatchQueue
工作,但它似乎是一个黑客:
Button(action: {
withAnimation(.linear(duration: 0.5)) {
self.pressed = !self.pressed
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(.linear(duration: 0.5)) {
self.pressed = !self.pressed
}
}
}) {
Wedge(startAngle: .init(degrees: 180), endAngle: .init(degrees: 270))
.fill(Color.red)
.frame(width: 200, height: 200)
.offset(x: 80, y: 80)
.scaleEffect(self.pressed ? 1.2 : 1.0)
}
Is the second way the right way to do this?第二种方法是正确的方法吗?
-- ——
Here is Wedge:这是楔子:
struct Wedge: Shape {
let startAngle: Angle
let endAngle: Angle
func path(in rect: CGRect) -> Path {
var path = Path()
let center = CGPoint(x: rect.midX, y: rect.midY)
path.addArc(center: center,
radius: min(rect.midX, rect.midY),
startAngle: startAngle,
endAngle: endAngle,
clockwise: false )
path.addLine(to: center)
path.closeSubpath()
return path
}
}
Probably you wanted this可能你想要这个
Button(action: {
withAnimation(.linear(duration: 3)){
self.pressed.toggle() // << here !!
}
print("B")
}) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.