1

我有一个黄色的容器,里面有一个绿色的视图。我想移动容器,同时隐藏/显示内部绿色视图,并带有动画。目前,我使用.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)
    }
}

如何使绿色视图随着黄色容器一起移动,因为它淡入淡出?最好,我想继续使用iforswitch语句进行插入/删除。

4

1 回答 1

1

您可以在动画时更改高度。

代码版本 #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

于 2021-12-07T01:03:08.803 回答