Last active
June 19, 2019 18:23
-
-
Save pteasima/051fd158866c38a8e78cdc645e895dae to your computer and use it in GitHub Desktop.
BindingObject auto didChange
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 | |
import Combine | |
@propertyWrapper struct MyObjectBinding<BindableObjectType: BindableObject> : DynamicViewProperty where BindableObjectType.PublisherType == PassthroughSubject<(), Never> { | |
init(initialValue: BindableObjectType) { | |
delegateValue = Wrapper(bindableObject: initialValue) | |
} | |
@dynamicMemberLookup struct Wrapper { | |
var bindableObject: BindableObjectType | |
subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<BindableObjectType, Subject>) -> Binding<Subject> { | |
Binding<Subject>(getValue: { | |
self.bindableObject[keyPath: keyPath] | |
}, setValue: { | |
self.bindableObject[keyPath: keyPath] = $0 | |
self.bindableObject.didChange.send(()) | |
}) | |
} | |
} | |
var delegateValue: Wrapper | |
var value: BindableObjectType { | |
get { | |
delegateValue.bindableObject | |
} | |
set { | |
delegateValue.bindableObject = newValue | |
} | |
} | |
} | |
final class DummyStore: BindableObject { | |
let didChange = PassthroughSubject<(), Never>() | |
var isOn: Bool = true | |
} | |
let _store = DummyStore() | |
struct ContentView : View { | |
@MyObjectBinding var store: DummyStore = _store | |
@ObjectBinding var nativeStore: DummyStore = _store | |
var body: some View { | |
List(0...100) { _ in | |
Toggle(isOn: self.$store.isOn) { | |
Text("is it on?") | |
} | |
} | |
} | |
} | |
#if DEBUG | |
struct ContentView_Previews : PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment