Displaying Badges in SwiftUI
In SwiftUI, badges are often used to display supplementary information or status indicators alongside a view component. They can help us draw the user’s attention to important details or provide additional context. SwiftUI offers several ways to implement badges, each with its own syntax and customization options.
1. Simple Badge
The simplest way to add a badge to a view is by using the .badge()
modifier and passing it a text value or a number. Here's an example:
List {
Text("Movies")
.badge(25)
}
In this case, the badge will display the number 25
next to the "Movies" text in the list. The badge will inherit the default style and appearance based on the system's design guidelines.
2. Customized Badge
If you want more control over the appearance of the badge, you can pass a custom view to the .badge()
modifier. This allows you to style the badge's text, color, and other properties. For instance:
List {
Text("Movies")
.badge(
Text("25")
.foregroundStyle(.green)
.bold()
)
}
Here, the badge will display the number 25
in a bold, green font. You can further customize the badge view by applying additional modifiers or creating a dedicated BadgeView
struct.