0

I'm facing challenge in swiftui animation. I'm trying to achieve top slider to animate only when current index element shown and animate for duration it is being displayed here 4 seconds.

Animation to achieve is top white layer to be filled from zero to full length of individual sliders

Current Code is

struct SliderElement: View {
    @Binding var minWidth: CGFloat
    @Binding var currentRunningIndex: Int
    var elementPosition: Int
    
    private var shouldAnimate: Bool {
        if currentRunningIndex == elementPosition {
            return true
        }
        return false
    }
    
    var body: some View {
        ZStack(alignment:.leading) {
            Capsule()
                .foregroundColor(Color.gray.opacity(0.6))
                .frame(width: 75, height: 4)
            
            if shouldAnimate {
                Capsule()
                    .foregroundColor(Color.white)
                    .frame(width: currentRunningIndex == elementPosition ? minWidth : 75, height: 4)
                    .animation(.easeInOut(duration: 4), value: minWidth)
            }
        }
    }
}

And it is being called from outer container, which changes current

  HStack {
      ForEach(0..<collection.count, id: \.self) { index in
        SliderElement(minWidth: $minWidth, currentRunningIndex: $currentIndex, elementPosition: index)
          }
       }

  func prepareAnimation()  {
     withAnimation {
      minWidth = maxWidth
    }

prepareAnimation is called using timer, and current displayed content also changed from parent container

Please assist, Thanks

Here is link for current behaviour https://drive.google.com/file/d/1GLPX-x0gpet0M_Og4U1a-QoZxBUzS8zr/view

https://drive.google.com/file/d/1cm6JYguPNYE6xb4AIGMBtFlF6DWTwV6V/view //shouldAnimate commented

khanHussain
  • 97
  • 1
  • 8
  • Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour) and see: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Your `SliderElement` which is really a progress bar (a slider is something different) should be dumb. You should just have a binding that sets the width of the top `Capsule()`. That binding should be tied to whatever timer keeps the ad on screen. You haven't given enough to go further with this. – Yrb Nov 12 '21 at 16:37
  • @Yrb Thanks for feedback and suggestion. Challenge here is in setting up conditional binding , meaning all four progress bar initially displayed with gray color, but when corresponding ad is being displayed, only that particular progress bar should be animating with white color – khanHussain Nov 13 '21 at 11:07
  • That is why we need the MRE. – Yrb Nov 13 '21 at 18:13

0 Answers0