Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Created October 23, 2024 12:38
Show Gist options
  • Select an option

  • Save takoikatakotako/f14baaa175beb9c5cebf83bbd0a43bcc to your computer and use it in GitHub Desktop.

Select an option

Save takoikatakotako/f14baaa175beb9c5cebf83bbd0a43bcc to your computer and use it in GitHub Desktop.
SwiftUIのTabViewのタブをコードから動的に切り替える
import SwiftUI
struct ContentView: View {
@State var selection: Int = 0
var body: some View {
TabView(selection: $selection) {
FirstView(selection: $selection)
.tabItem {
Image(systemName: "house")
.renderingMode(.template)
Text("FirstView")
}
.tag(0)
SecondView(selection: $selection)
.tabItem {
Image(systemName: "books.vertical")
.renderingMode(.template)
Text("SecondView")
}
.tag(1)
}
}
}
import SwiftUI
struct FirstView: View {
@Binding var selection: Int
var body: some View {
VStack {
Text("FirstView")
Button {
selection = 1
} label: {
Text("Go to SecondView")
}
}
}
}
import SwiftUI
struct SecondView: View {
@Binding var selection: Int
var body: some View {
VStack {
Text("SecondView")
Button {
selection = 0
} label: {
Text("Go to FirstView")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment