简体   繁体   中英

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM