Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created July 30, 2020 15:33
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 JadenGeller/03942c97b3bb4254b3a7ae484e4b5e25 to your computer and use it in GitHub Desktop.
Save JadenGeller/03942c97b3bb4254b3a7ae484e4b5e25 to your computer and use it in GitHub Desktop.
onCadence
struct CadenceViewModifier: ViewModifier {
let timeInternal: Double
let action: () -> Void
@State var lastFire: Date?
func body(content: Content) -> some View {
content
.onAppear() // https://stackoverflow.com/questions/61190398/swiftui-viewmodifier-doesnt-listen-to-onreceive-events
.onReceive(Timer.publish(every: timeInternal + (lastFire?.timeIntervalSinceNow ?? 0), on: .main, in: .default).autoconnect()) { _ in
self.lastFire = Date()
action()
}
}
}
extension View {
func onCadence(timeInterval: Double, action: @escaping () -> ()) -> some View {
modifier(CadenceViewModifier(timeInternal: timeInterval, action: action))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment