簡體   English   中英

SwiftUI - 動畫視圖過渡和 position 同時更改

[英]SwiftUI - Animate view transition and position change at the same time

我有一個黃色的容器,里面有一個綠色的視圖。 我想移動容器,同時隱藏/顯示內部綠色視圖,使用 animation。 目前,我使用.offset進行移動,並使用if語句進行綠色視圖的轉換。

問題是,雖然黃色容器移動了,但綠色視圖卻沒有。 它只是在目標偏移處淡入淡出。 我希望它也能沿着黃色容器移動。

這是我目前得到的 這就是我要的
黃色容器左右移動,而綠色內部視圖淡入淡出。綠色視圖保持在右側 黃色容器隨着綠色內部視圖左右移動,綠色內部視圖也會淡入淡出。

這是我的代碼:

struct ContentView: View {
    @State var showingSubview = false
    
    var body: some View {
        VStack {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }
            
            if showingSubview {
                Text("Subview")
                    .padding()
                    .background(Color.green)
            }
        }
        .padding()
        .background(Color.yellow)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

如何使綠色視圖隨着黃色容器一起移動,因為它淡入淡出? 最好,我想繼續使用ifswitch語句進行插入/刪除。

您可以在動畫時更改高度。

代碼版本 #1

這不會褪色並出現在黃色矩形內。

代碼:

struct ContentView: View {
    @State var showingSubview = false

    var body: some View {
        VStack(spacing: 0) {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }

            Text("Subview")
                .padding()
                .background(Color.green)
                .padding(.top)
                .frame(height: showingSubview ? nil : 0, alignment: .top)
                .clipped()
        }
        .padding()
        .background(Color.yellow)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

結果#1

結果 1

代碼版本 #2

如您的 GIF 所示,此版本將淡出並出現在底部邊緣。

代碼:

struct ContentView: View {
    @State var showingSubview = false

    var body: some View {
        VStack(spacing: 0) {
            Button("Show Subview") {
                withAnimation(.easeInOut(duration: 2)) {
                    showingSubview.toggle()
                }
            }

            Text("Subview")
                .padding()
                .background(Color.green)
                .padding(.top)
                .frame(height: showingSubview ? nil : 0, alignment: .top)
                .padding(.bottom)
                .background(Color.yellow)
                .clipped()
                .opacity(showingSubview ? 1 : 0)
        }
        .padding([.horizontal, .top])
        .background(Color.yellow)
        .padding(.bottom)
        .offset(x: showingSubview ? 150 : 0, y: 0)
    }
}

結果#2

結果 2

暫無
暫無

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

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