为什么 SwiftUI 不透明度动画在 Gesture 的 onEnded 方法中失败?

Why does SwiftUI opacity animation fail in Gesture's onEnded method?

如下图所示,第二次点击紫色矩形不会触发蓝色矩形淡入的动画。这是 Bug 还是模糊功能?

感谢您的热心回复!

trying to toggle the opacity of the big blue rectangle with animation (sorry, not enough reputation to post images)

struct FadeTestView: View {
  @State var fade: Bool = false
  var body: some View {
    VStack{
      Rectangle().fill(.blue).frame(width: 100, height: 100, alignment: .center)
        .opacity(fade ? 0 : 1)
      
      Button(action: {
        withAnimation(.easeInOut(duration: 2)){ fade.toggle() }
      }){
        Circle().fill(.yellow).frame(width: 50, height: 50, alignment: .center)
      }
      
      Rectangle().fill(.purple).frame(width: 50, height: 50, alignment: .center)
        .gesture(TapGesture().onEnded{
          withAnimation(.easeInOut(duration: 2)){ fade.toggle() }
        })
    }
  }
}

我认为这是 .opacity 的错误。变通办法似乎根本就没有一直更改为 0。

        Rectangle()
            .fill(.blue)
            .frame(width: 100, height: 100, alignment: .center)
            .opacity(fade ? 0.01 : 1)

任何低于 .opacity 的值都被视为 0,但 .01 实际上是透明的。

如果只是为了改变不透明度,请使用线性

struct FadeTestView: View {
@State var fade: Bool = false
var body: some View {
VStack{
  Rectangle().fill(.blue).frame(width: 100, height: 100, alignment:       .center)
    
    .opacity(fade ? 0 : 1)
  
  Button(action: {
      withAnimation(.linear(duration: 2)){ fade.toggle() }
  }){
    Circle().fill(.yellow).frame(width: 50, height: 50, alignment: .center)
  }
  
  Rectangle().fill(.purple).frame(width: 50, height: 50, alignment: .center)
        .onTapGesture() {
            withAnimation(.linear(duration: 2)){
                fade.toggle()
            }
        }
       
}
}

}