Skip to content

Instantly share code, notes, and snippets.

@BjornRuud
Created March 9, 2021 14:33
Show Gist options
  • Save BjornRuud/bc75101626d429d993972422deb995c7 to your computer and use it in GitHub Desktop.
Save BjornRuud/bc75101626d429d993972422deb995c7 to your computer and use it in GitHub Desktop.
SwiftUI View.onChange(of:perform:) reimplementation for iOS 13
import SwiftUI
private struct ViewOnChangeValueObserver<Content: View, Value: Equatable>: View {
let content: Content
let value: Value
let action: (Value) -> Void
@State private var oldValue: Value
init(
value: Value,
action: @escaping (Value) -> Void,
content: Content
) {
self.value = value
self.action = action
self.content = content
self._oldValue = State(initialValue: value)
}
var body: some View {
if oldValue != value {
DispatchQueue.main.async {
oldValue = value
action(value)
}
}
return content
}
}
extension View {
func onChangeValue<Value>(
of value: Value,
perform action: @escaping (Value) -> Void
) -> some View where Value: Equatable {
ViewOnChangeValueObserver(value: value, action: action, content: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment