Mane Manero
Mane Manero

Reputation: 3788

SwiftUI: animating between Single and HStack views

Goal:

1- Shows a view (Blue) that covers entire screen enter image description here 2- When tapped on bottom (top right corner), it shows an HStack animating right side HStack (Green) "Slide Offset animation". enter image description here

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

The code works, however I cannot get the Green "Slide Offset animation" to work. Really appreciate any help! : )

Upvotes: 0

Views: 1693

Answers (1)

John M.
John M.

Reputation: 9473

Instead of using the if conditional, you need the green rectangle to be already present, and just offscreen. When showgreen toggles, you need to shrink the size of the blue rectangle, which will make room for the green rectangle.

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

Upvotes: 2

Related Questions