I need to prevent users from selecting a different tab
in TabView
. The solution using onChange
no longer works on iOS 18.
Steps to reproduce:
- Navigate from Home → Details → (UI works as expected)
- Navigate from Home → Directory (blocked by
onChange
) → Details (UI breaks) - Navigate from Home → Directory (blocked by
onChange
) → Details (UI breaks) -> Back (Now we can't navigate to Details anymore).
struct TabViewBugView: View {
enum AppTab {
case home
case directory
}
@State private var selection: AppTab = .home
var body: some View {
TabView(selection: $selection) {
NavigationStack {
NavigationLink {
VStack {
Text("Details")
Spacer()
}
} label: {
Text("Go to Details")
}
Text("HomeView")
}
.tabItem {
Label("Home", systemImage: "house")
}
.tag(AppTab.home)
Text("Directory")
.tabItem {
Label("Directory", systemImage: "folder")
}
.tag(AppTab.directory)
}
.onChange(of: selection) { oldValue, newValue in
print("\(oldValue) -> \(newValue)")
if newValue == .directory {
selection = oldValue
}
}
}
}
How can I properly prevent tab selection without breaking the UI?
I need to prevent users from selecting a different tab
in TabView
. The solution using onChange
no longer works on iOS 18.
Steps to reproduce:
- Navigate from Home → Details → (UI works as expected)
- Navigate from Home → Directory (blocked by
onChange
) → Details (UI breaks) - Navigate from Home → Directory (blocked by
onChange
) → Details (UI breaks) -> Back (Now we can't navigate to Details anymore).
struct TabViewBugView: View {
enum AppTab {
case home
case directory
}
@State private var selection: AppTab = .home
var body: some View {
TabView(selection: $selection) {
NavigationStack {
NavigationLink {
VStack {
Text("Details")
Spacer()
}
} label: {
Text("Go to Details")
}
Text("HomeView")
}
.tabItem {
Label("Home", systemImage: "house")
}
.tag(AppTab.home)
Text("Directory")
.tabItem {
Label("Directory", systemImage: "folder")
}
.tag(AppTab.directory)
}
.onChange(of: selection) { oldValue, newValue in
print("\(oldValue) -> \(newValue)")
if newValue == .directory {
selection = oldValue
}
}
}
}
How can I properly prevent tab selection without breaking the UI?
Share Improve this question asked 1 hour ago Danylo HorielovDanylo Horielov 692 bronze badges 2- A custom tab bar would be one way to fix, then you can disable any buttons that are supposed to be, well, disabled. See this answer for an example implementation. – Benzy Neez Commented 52 mins ago
- Btw, Apple's Human Interface Guidelines discourage this type of behaviour: Don’t disable or hide tab bar buttons, even when their content is unavailable. Having tab bar buttons available in some cases but not others makes your app’s interface appear unstable and unpredictable. If a section is empty, explain why its content is unavailable. – Benzy Neez Commented 47 mins ago
1 Answer
Reset to default 0cool. this code veru nice, relli nice