TabBar
TabBar copied to clipboard
Updating Selection from Another View
How I can updated selected State if I'm navigating to view (presented TabBar), but not from TabBar, like from button inside of another view, or using NavigationLink in another view.
Thank you
View with TabBar
struct GeneralView View {
enum Item: Int, Tabbable {
case home = 0
case letters
case heritage
case bookmarks
case third
var icon: String {
switch self {
case .letters: return "textformat"
case .heritage: return "command"
case .home: return "house.fill"
case .third: return "quote.bubble"
case .bookmarks: return "bookmark.fill"
}
}
var title: String {
switch self {
case .letters: return "Letters"
case .heritage: return "Heritage"
case .home: return "Arageel"
case .third: return "Third"
case .bookmarks: return "Bookmarks"
}
}
}
@State private var selection: Item = .home
@State private var visibility: TabBarVisibility = .visible
var body: some View {
TabBar(selection: $selection, visibility: $visibility) {
LettersGridView()
.tabItem(for: Item.letters)
HeritageZineHomeView()
.environmentObject(RSSReader())
.tabItem(for: Item.heritage)
HomeView()
.tabItem(for: Item.home)
PBHomeView()
.tabItem(for: Item.third)
PBHomeView()
.tabItem(for: Item.bookmarks)
}
.tabBar(style: CustomTabBarStyle())
.tabItem(style: CustomTabItemStyle())
.ignoresSafeArea(.all)
}
}
Another View
var stickyHeaderView: some View {
HStack {
Text("Heritage").modifier(MainStoryTitle(color: "BlackDark"))
Spacer()
NavigationLink (
destination:
HeritageHomeView()
) {
Image(systemName: "arrow.up.forward")
.foregroundColor(Color("Orange"))
}
}
.padding(.horizontal, 30)
}
Use a @Binding var selection: Item
in Another View and pass it $selection
. This will allow you to update the state.
Reci
Use a
@Binding var selection: Item
in Another View and pass it$selection
. This will allow you to update the state.
Receiving error
Type 'Binding<Item>' has no member 'home'
that is just telling that you probably removed home from your enum or that it is taking some other Item
type instead of your enum (the naming is very generic).
It would be something like this:
struct GeneralView View {
@State private var selection: Item = .home
var body: some View {
ZStack {
TabBar(selection: $selection, visibility: $visibility) {
// ... some more code....
}
StickyHeaderView(selection: $selection)
}
}
// ... some more code....
struct StickyHeaderView: View {
@Binding var selection: Item
var body: some View {
Button("Selection to letters") {
selection = .letters
}
}