Home > Software engineering >  Replicate side bar animation slide not working
Replicate side bar animation slide not working

Time:07-16

I am trying to replicate social media side bar which slide from left to right when we click on something But the way it slides is so laggy and on top of that it's not full height of screen and when it goes off it slide to middle instead of right to left. How can I fix this please?

 struct MySideBarMap: View { 
 var totalActivities: Int = 15
@State var mySideBar: Bool = false
var body: some View {
    ZStack() {
        VStack() {
            ForEach(0...totalActivities, id: \.self) { ac in
                VStack() {
                    Image(systemName: "figure.cooldown")
                        .foregroundColor(.blue)
                    Text("\(ac)")
                }
                .onTapGesture {
                    withAnimation {
                        mySideBar.toggle()
                    }
                }
            }
        }
        HStack() {
            if mySideBar {
                Rectangle()
                    .frame(width: 150)
                    .transition(.slide)
            }
            Spacer()
        }
    }
  }
  }

CodePudding user response:

For this case, working with the width of your side bar for animation and on/off is better.

To fix this, make your width value as 0 for off and as 150 for on. Also, make your side bar ignores the safe area to make it fills the max height of your screen.

Try the code below the image: enter image description here

import SwiftUI

struct ContentView: View {
var totalActivities: Int = 15
@State var width = CGFloat(0)
var body: some View {
    ZStack() {
        VStack() {
            ForEach(0...totalActivities, id: \.self) { ac in
                VStack() {
                    Image(systemName: "figure.cooldown")
                        .foregroundColor(.blue)
                    Text("\(ac)")
                }
                .onTapGesture {
                    if width == 0 {
                        withAnimation {
                            width = 150
                        }
                    }
                    else {
                        withAnimation {
                            width = 0
                        }
                    }
                }
            }
        }
        HStack() {
            Rectangle()
                .frame(width: width)
                .edgesIgnoringSafeArea(.all)
            Spacer()
        }
    }
  }
}
  • Related