Skip to content

Instantly share code, notes, and snippets.

@badrinathvm
Last active April 2, 2020 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badrinathvm/13b79f1d6dfd30ea54a106dc1d805953 to your computer and use it in GitHub Desktop.
Save badrinathvm/13b79f1d6dfd30ea54a106dc1d805953 to your computer and use it in GitHub Desktop.
ProgressView of SwiftUI
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