'How to clear badge in TabView on SwiftUI
Showing a badge is easy enough using the .badge(content) modifier, but to remove it the .badge(nil) modifier doesn't work despite being, apparently, an option in the docs.
TabView {
VStack {
Text("Tab 1")
}
.tabItem {
Text("Tab 1")
}
.badge(1) // works as expected
VStack {
Text("Tab 2")
}
.tabItem {
Text("Tab 2")
}
.badge(nil) // doesn't work
VStack {
Text("Tab 3")
}
.tabItem {
Text("Tab 3")
}
.badge(elementsCount > 0 ? elementsCount : nil) // What I wan't to actually do, which of course also doesn't work
}
What is it I am not getting? Or the only option to display a badge using a condition is to create an entirely different view path with an alternate but identical tabitem except with no badge?
Solution 1:[1]
The badge is shown when it's not zero. So, the following works:
TabView {
VStack {
Text("Tab 1")
}
.tabItem {
Text("Tab 1")
}
.badge(1) // works as expected
VStack {
Text("Tab 2")
}
.tabItem {
Text("Tab 2")
}
.badge(0) // badge not shown
VStack {
Text("Tab 3")
}
.tabItem {
Text("Tab 3")
}
.badge(elementsCount) // When zero, the badge is not shown
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HunterLion |
