[英]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)
}
}
如何使綠色視圖隨着黃色容器一起移動,因為它淡入淡出? 最好,我想繼續使用if
或switch
語句進行插入/刪除。
您可以在動畫時更改高度。
這不會褪色並出現在黃色矩形內。
代碼:
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)
}
}
如您的 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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.