Created
July 30, 2020 15:33
-
-
Save JadenGeller/03942c97b3bb4254b3a7ae484e4b5e25 to your computer and use it in GitHub Desktop.
onCadence
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 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