如何在动画结束时设置属性或任何回调? [复制]
Posted
技术标签:
【中文标题】如何在动画结束时设置属性或任何回调? [复制]【英文标题】:How to set a property or any callbacks upon the finishing of an animation? [duplicate] 【发布时间】:2021-10-31 03:10:58 【问题描述】:下面是一个示例代码,其中默认显示一个矩形。有两个按钮可以隐藏和显示矩形。我希望仅在隐藏矩形时才显示“显示”按钮,而仅在显示矩形时才显示“隐藏”按钮。矩形状态的转换是通过动画完成的。
问题是由于动画的原因,如果我按下“隐藏”按钮,“显示”按钮会立即显示,而无需等待矩形完全从不透明度 1 过渡到 0。如何在动画的完成,所以 showButtonEnabled 属性仅在动画结束后设置?
@State var showRect = true
@State var showButtonEnabled = false
var myTestButton: some View
HStack
Rectangle().fill()
.opacity(showRect ? 1 : 0)
Button("Show")
withAnimation(.linear(duration: 3))
showRect = true
// only do the following at the completion of the animation
showButtonEnabled = false
.disabled(!showButtonEnabled)
Button("Hide")
withAnimation(.linear(duration: 3))
showRect = false
// only do the following at the completion of the animation
showButtonEnabled = true
.disabled(showButtonEnabled)
【问题讨论】:
【参考方案1】:使用DispatchQueue
将值更改为变量。
var myTestButton: some View
HStack
Rectangle().fill()
.opacity(showRect ? 1 : 0)
Button("Show")
withAnimation(.linear(duration: 3))
showRect = true
// only do the following at the completion of the animation
DispatchQueue.main.asyncAfter(deadline: .now() + 3)
showButtonEnabled = false
.disabled(!showButtonEnabled)
Button("Hide")
withAnimation(.linear(duration: 3))
showRect = false
// only do the following at the completion of the animation
DispatchQueue.main.asyncAfter(deadline: .now() + 3)
showButtonEnabled = true
.disabled(showButtonEnabled)
【讨论】:
以上是关于如何在动画结束时设置属性或任何回调? [复制]的主要内容,如果未能解决你的问题,请参考以下文章