Add a badge to TabView items in SwiftUI

In this tutorial, we will see how to add badges to TabView items in SwiftUI.

We can add a number or text as a badge to the TabView items using the badge() modifier. This is particularly useful for highlighting additional status information, such as displaying an unread message count or a label over a tab icon.

Using an integer value as a badge value

Suppose we want to display the number 7 over a tab item, we can simply do that by specifying an integer value within the badge() modifier.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            Text("Welcome to CodeSpeedy")
                .tabItem {
                    Label("Notifications", systemImage: "bell")
                }
                .badge(7)
        }
    }
}

Output:

 

Using an integer as a badge value in SwiftUI

Using a string as a badge value

We can also specify a string as the badge value. Here I will show “New” over the bell icon instead of the integer value 7.

We can simply do that by specifying the string value “New” within the badge() modifier.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            Text("Welcome to CodeSpeedy")
                .tabItem {
                    Label("Notifications", systemImage: "bell")
                }
                .badge("New") 
        }
    }
}

Output:

Using a string as a badge value in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *