Hello, I've been trying to learn about the Binding mechanism. I have an example where I build a Binding from a set/get class+ReferenceWritableKeyPath. Most of the data flow is working but SwiftUI is not invalidating the toggle and doesn't refresh the toggle status. Any idea?
//
// ContentView.swift
// swiftui-play
//
// Created by Daniel Pereira on 23/10/2019.
// Copyright © 2019 Daniel Pereira. All rights reserved.
//
import SwiftUI
import Combine
extension Binding {
init<A>(keyPath: ReferenceWritableKeyPath<A, Value>, settings: A) {
self.init(
get: { settings[keyPath: keyPath] },
set: { settings[keyPath: keyPath] = $0}
)
}
}
final class ClassA {
var on: Bool = true
}
struct ContentView: View {
@Environment(\.classA) private var classA
var body: some View {
let toggled = Binding(keyPath: \.on, settings: classA)
return Form {
Toggle(isOn: toggled) {
Text("Show welcome text")
}
}.padding(5)
}
}
let classA = ClassA()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environment(\.classA, classA)
}
}
struct ClassAEnvironmentKey: EnvironmentKey {
static var defaultValue = ClassA()
}
extension EnvironmentValues {
var classA: ClassA {
get { self[ClassAEnvironmentKey.self] }
set { self[ClassAEnvironmentKey.self] = newValue}
}
}