Created
March 9, 2021 14:33
-
-
Save BjornRuud/bc75101626d429d993972422deb995c7 to your computer and use it in GitHub Desktop.
SwiftUI View.onChange(of:perform:) reimplementation for iOS 13
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
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