I am currently trying to pass the currently selected picker tab/tabview and then pass it to a class in order to change a variable based on the said tab.
The relevant parts of my code are here. Each of the tabs go to a separate view
struct ContentView: View {
@State var selectedRoute: Tabs = .firstTab
var body: some View {
VStack{
Picker("", selection: $selectedRoute){
Text("Red").tag(Tabs.firstTab)
Text("Green").tag(Tabs.secondTab)
Text("Blue 1").tag(Tabs.thirdTab)
Text("Blue 2").tag(Tabs.fourthTab)
Text("Wings").tag(Tabs.fifthTab)
}.pickerStyle(SegmentedPickerStyle())
switch selectedRoute{
case .firstTab: FirstTabView()
case .secondTab: SecondTabView()
case .thirdTab: ThirdTabView()
case .fourthTab: FourthTabView()
case .fifthTab: FifthTabView()
}
}
}
}
enum Tabs: String, CaseIterable, Identifiable{
case firstTab, secondTab, thirdTab, fourthTab, fifthTab
var id: Self { self }
}
class ContentModel: ObservableObject {
@Published var records = [Record]()
@State var routeString: String = "red"
@State var sRoute = ContentView().selectedRoute
init() {
getData()
}
func getData(){
if sRoute == Tabs.firstTab{
routeString = "Red"
}else if sRoute == Tabs.secondTab{
routeString = "Green"
}else if ContentView().selectedRoute == Tabs.thirdTab{
routeString = "Blue"
}else if ContentView().selectedRoute == Tabs.fourthTab{
routeString = "Purple"
}else if ContentView().selectedRoute == Tabs.fifthTab{
routeString = "Yellow"
}else{
routeString = ""
}
....
}
I want to get the currently selected tab into the contentmodel class so I can make a dynamic url string that changes based on said tabs. I have tried various different things such as the above state vars and the if/else-if statements, but I’ve found the issue is stemming from the @state var in the contentview struct never changing even when changing tabs. Is the some sort of listener I need to implement or like an .onChange(etc)?
P.S. I have seen other articles relating to this that uses a foreach loop inside of a picker, but with how I have my contentview set up I feel like I would have to change a lot of code. I could be overthinking that issue though. ex: How to assign a value selected from a Picker to a variable in another class?