Alejandro
Alejandro

Reputation: 379

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?

Upvotes: 0

Views: 568

Answers (1)

HunterLion
HunterLion

Reputation: 4006

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
}

Upvotes: 2

Related Questions