Hi, I'm new to swiftUI and am having a few issues getting my head around how it works.
My immediate issue is that I'm getting a response from an api in the form of a JSON string that I'm splitting into 2 arrays of my data model.
This works fine and I have 2 lists in my view that if I change the binding in my list, the data changes to the other list.
I can't seem to get it to change on a button click though. I want 2 buttons (one for each list) and clicking them will change the binding.
I've got to the stage where I feel I'm soooooo close, but am missing something obvious.
This is the code in my view:
So, I have my @State variables list1 and list2 and if I change which one appears in viewingModels, the list changes.
How can I do this on the button presses?
Thanks
My immediate issue is that I'm getting a response from an api in the form of a JSON string that I'm splitting into 2 arrays of my data model.
This works fine and I have 2 lists in my view that if I change the binding in my list, the data changes to the other list.
I can't seem to get it to change on a button click though. I want 2 buttons (one for each list) and clicking them will change the binding.
I've got to the stage where I feel I'm soooooo close, but am missing something obvious.
This is the code in my view:
Code Block struct SplitView: View { @EnvironmentObject var viewRouter: ViewRouter @State var list1 = [MyModel]() @State var list2 = [MyModel]() private var viewingModels: [MyModel] { list1 } var body: some View { HStack { Button(action: { //selected = 1 }){ Text("List 1") } Button(action: { //selected = 2 }){ Text("List 2") } } List(viewingModels, id: \.ID) { myitem in HStack(alignment: .center) { VStack(alignment: .leading) { Text(myitem.Name) .font(.subheadline) .fontWeight(.bold) Spacer() } } } //end list .onAppear(perform: loadList) Spacer() } }
So, I have my @State variables list1 and list2 and if I change which one appears in viewingModels, the list changes.
How can I do this on the button presses?
Thanks
I may be missing something, but why don't you simply add an @State variable to choose the lists?
Code Block struct SplitView: View { @EnvironmentObject var viewRouter: ViewRouter @State var list1 = [MyModel]() @State var list2 = [MyModel]() @State var selected: Int = 1 private var viewingModels: [MyModel] { switch selected { case 1: return list1 case 2: return list2 default: return [] } } var body: some View { HStack { Button(action: { selected = 1 }){ Text("List 1") } Button(action: { selected = 2 }){ Text("List 2") } } List(viewingModels, id: \.ID) { myitem in HStack(alignment: .center) { VStack(alignment: .leading) { Text(myitem.Name) .font(.subheadline) .fontWeight(.bold) Spacer() } } } .onAppear(perform: loadList) Spacer() } }