簡體   English   中英

為什么 SwiftUI opacity animation 在 Gesture 的 onEnded 方法中失敗?

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

如下圖所示,在紫色矩形上的第二次點擊不會觸發 animation 以使藍色矩形淡入。這是錯誤還是晦澀的功能?

感謝您的回復!

試圖用 animation 切換藍色大矩形的不透明度(抱歉,沒有足夠的聲譽來發布圖像)

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()
            }
        }
       
}
}

}

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM