I have the following construct
import SwiftUI
class TopClass: ObservableObject {
@Published var someArr = [SomeClass(), SomeSubclass()]
}
class SomeClass: Identifiable {
let id = UUID()
}
class SomeSubclass: SomeClass {
var toggle = true
}
struct ContentView: View {
@ObservedObject var topClass = TopClass()
var body: some View {
ForEach($topClass.someArr) {
$value in
if let someSubclass = $value as? SomeSubclass {
Toggle("Test", isOn: someSubclass.toggle)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I can`t figure out if it is possible to somehow bind someSubclass.toggle to isOn of the Toggle. I solution or a hint to where I could research this would be very appreciated.
CodePudding user response:
If you are really hell-bent on using this approach, then try this example code:
struct ContentView: View {
@ObservedObject var topClass = TopClass()
var body: some View {
ForEach($topClass.someArr) { $value in
if let someSubclass = $value.wrappedValue as? SomeSubclass {
Toggle("test", isOn: Binding<Bool> (
get: { someSubclass.toggle },
set: {
topClass.objectWillChange.send()
someSubclass.toggle = $0
})
)
}
}
}
}