SwiftUI:在 Single 和 HStack 视图之间设置动画

SwiftUI: animating between Single and HStack views

目标:

1- 显示覆盖整个屏幕的视图(蓝色) 2- 当点击底部(右上角)时,它会显示一个 HStack 动画右侧 HStack(绿色)"Slide Offset animation"。

import SwiftUI

struct ContentView: View {

    @State var showgreen = false


    var body: some View {


    NavigationView {

        HStack {
            Rectangle()
            .foregroundColor(.blue)

            if showgreen  {
            Rectangle()
            .foregroundColor(.green)
            .offset(x: showgreen ? 0 : UIScreen.main.bounds.width)
            .animation(.easeInOut)
            }

           }

    .navigationBarItems(trailing:
      Button(action: { self.showgreen.toggle() }) {
              Image(systemName: "ellipsis")
              })
       }

    .navigationViewStyle(StackNavigationViewStyle())


    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        .colorScheme(.dark)
        .previewDevice("iPad Pro (12.9-inch) (3rd generation)")
    }
}

代码有效,但我无法使绿色 "Slide Offset animation" 正常工作。非常感谢任何帮助! :)

而不是使用 if 条件,您需要绿色矩形已经存在,并且刚好在屏幕外。 showgreen切换时,需要缩小蓝色矩形的大小,为绿色矩形腾出空间。

struct ContentView: View {
    @State var showgreen = false

    var body: some View {
        NavigationView {
            HStack {
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(width: showgreen ? UIScreen.main.bounds.width / 2 : UIScreen.main.bounds.width)
                    .animation(.easeInOut)

                Rectangle()
                    .foregroundColor(.green)
                    .animation(.easeInOut)
            }
            .navigationBarItems(trailing:
                Button(action: { self.showgreen.toggle() }) {
                    Image(systemName: "ellipsis")
            })
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}