I have got two tabItems in TabView with FirstScreen and PlacesScreen. FirstScreen contains picker with items located in array in the model PlacesViewModel. The same model is used for the list from the second tabItem on PlacesScreen. By choosing a particular item in picker and pressing button, I have to open the second tabItem and open a particular row in the list on PlacesScreen. I have figured out how to open the second tabItem but stuck with opening a particular row.
The first screen code with picker and button:
struct FirstScreen: View {
@EnvironmentObject var placesViewModel: PlacesViewModel
@State var placeChoice = 0
@Binding var tabSelection: Int
var body: some View {
NavigationView {
Form {
VStack {
Picker("Places", selection: $placeChoice) {
ForEach(0 ..< placesViewModel.places.count) { index in
Text(placesViewModel.places[index].name)
.tag(index)
}
}.pickerStyle(WheelPickerStyle())
Button {
tabSelection = 1
} label: {
Text("Show place")
.font(.system(size: 20))
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}
}
}
.navigationTitle("First Screen")
}
}
}
struct FirstScreen_Previews: PreviewProvider {
static var previews: some View {
FirstScreen(tabSelection: .constant(0))
}
}
The second screen with a List:
struct PlacesScreen: View {
var body: some View {
PlacesList()
}
}
struct PlacesScreen_Previews: PreviewProvider {
static var previews: some View {
PlacesScreen()
}
}
struct PlacesList: View {
@EnvironmentObject var placesViewModel: PlacesViewModel
var body: some View {
NavigationView {
List(placesViewModel.places) { place in
NavigationLink {
PlaceScreen(place: place)
} label: {
HStack {
place.image
.resizable()
.frame(width: 50, height: 50)
Text(place.name)
Spacer()
}
}
}
.navigationTitle(placesViewModel.title)
}
}
}
struct PlacesList_Previews: PreviewProvider {
static var previews: some View {
PlacesList()
}
}
Here is the TabView code:
struct ContentView: View {
@State var tabSelection: Int = 0
var body: some View {
TabView(selection: $tabSelection) {
FirstScreen(tabSelection: tabSelection)
.tag(0)
.tabItem {
Label("First Screen", systemImage: "list.bullet.rectangle")
}
PlacesScreen()
.tag(1)
.tabItem {
Label("Places", systemImage: "tray.2.fill")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Thank you in advance for your help!
