I am new to programming and SwiftUI so this will be basic. (this code is a combination of different ObservableObject
tutorials I found so there are unnecessary/wrong steps, in fact, the whole thing might be wrong). Any help is greatly appreciated!!
I have a Main listview of four 'switch' rows, each with a switchTask
property. The detail view is a Tabview with a few screens. When a user updates the switchTask
in any detail tabviews, I need that task property to update in the main listview for the respective SwitchRow
.
My ObservableObject is an array switches
. I am having trouble figuring out how to correctly pass each Switch instance to the Tabview details (PluggedInDetail
) so the corresponding switchTask
in main listview is updated. Should I be using EnvironmentObject
instead?
ObservableObject and Row:
import SwiftUI
import Combine
class Switch: ObservableObject, Identifiable {
let id = UUID()
@Published var switchName: String
@Published var switchTask: String
init (switchName: String, switchTask: String) {
self.switchName = switchName
self.switchTask = switchTask
}
}
class Switches: ObservableObject {
//private init() { }
static let shared = Switches()
@Published var switches: [Switch]
init() {
//switchTask is to be updated on tabview detail
self.switches = [
Switch(switchName: "Switch Input 1", switchTask: ""),
Switch(switchName: "Switch Input 2", switchTask: ""),
Switch(switchName: "Switch Input 3", switchTask: ""),
Switch(switchName: "Switch Input 4", switchTask: "")]
}
}
struct SwitchRow: View {
@ObservedObject var myswitch: Switch
var body: some View {
HStack{
Image(systemName: "circle")
VStack{
Text(myswitch.switchName)
Text(myswitch.switchTask)
}
}
}
}
ContentView:
struct ContentView: View {
@ObservedObject var myswitches: Switches = .shared
var body: some View {
NavigationView{
VStack {
List(Array(myswitches.switches.enumerated()), id: \.element.id) { (i, Switch) in
NavigationLink(destination: tabDetail()){
SwitchRow(myswitch: self.myswitches.switches[i])
}
}
}
}
}
}
struct tabDetail: View {
@ObservedObject var detailSwitches: Switches = .shared
var body: some View {
TabView {
PluggedInDetail()
.tabItem {
Text("Plugged In")
}
TVDetail()
.tabItem {
Text("TV")
}
}
}
}
Detail View: (currently hardcoded the array element to update for Switch Input 1. This is where I need help)
import SwiftUI
import Combine
struct PluggedInDetail: View {
@ObservedObject var detailSwitches: Switches = .shared
var body: some View {
VStack {
// switchName should display in the text
Text(self.detailSwitches.switches[0].switchName)
Button(action: {
//This should update switchTask for whichever switch element is selected
self.detailSwitches.switches[0].switchTask = "Direct Press"
}) {
Text("Add Direct Press")
}
}
}
}