Last active
April 2, 2020 05:29
-
-
Save badrinathvm/13b79f1d6dfd30ea54a106dc1d805953 to your computer and use it in GitHub Desktop.
ProgressView of SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ProgressView: View { | |
@State private var currentIndex:Int = 0 | |
@State private var maxIterations:Int = 0 | |
@State private var publisher = PassthroughSubject<AnimationStatus, Never>() | |
var body: some View { | |
HStack(spacing: 8) { | |
ForEach(0..<5) { index in | |
RectangleView(index: index, publisher: self.publisher) | |
} | |
}.onAppear { | |
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { (timer) in | |
//repeat the animation for three times | |
if self.maxIterations < 3 { | |
if self.currentIndex < self.maxCount { | |
self.publisher.send(AnimationStatus.start(index: self.currentIndex)) | |
self.currentIndex += 1 | |
} else if self.currentIndex == self.maxCount { | |
self.currentIndex = 0 | |
self.maxIterations += 1 | |
} | |
} else { | |
// sending data via publisher | |
self.publisher.send(.stopAll) | |
self.publisher.send(.start(index: 0)) | |
} | |
} | |
} | |
} | |
struct RectangleView: View { | |
var index: Int | |
@State private var animate = false | |
var publisher:PassthroughSubject<AnimationStatus, Never> | |
var body: some View { | |
Rectangle() | |
.foregroundColor(Color.green) | |
.frame(width: 50, height: 10) | |
.opacity(animate ? 1: 0.2) | |
.animation(.easeInOut) | |
.onReceive(publisher) { (value) in | |
switch value { | |
case .start(let index): | |
if index == self.index { | |
self.animate = true | |
} else { | |
self.animate = false | |
} | |
case .stop(let index): | |
if index == self.index { | |
self.animate = false | |
} | |
case .stopAll: | |
self.animate = false | |
} | |
} | |
} | |
} | |
enum AnimationStatus { | |
case start(index:Int) | |
case stop(index:Int) | |
case stopAll | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment