Show badge on List Row in SwiftUI
In this tutorial, we will see how to show a badge on a list row in SwiftUI.
A badge is like a little tag or number that we can see on icons or next to items in apps.
For example, in an email app, a badge might show a number indicating how many new emails we have. In a to-do list app, it might show how many tasks we still need to do.
We can show a badge to any List row by using the badge()
modifier. Now, follow the approaches below to achieve this task.
Create a badge with an integer and a string
We can show a badge on a list row passing an integer value or a string within the badge()
modifier.
Badges with integer values are commonly used to show counts, such as the amount of unread emails or tasks on a to-do list.
Sometimes, we can’t represent all information as numbers, such as whether the WiFi or Bluetooth is turned on or off. That’s where badges with string values come in handy, they are perfect for clearly displaying textual information.
Example
List { Text("Inbox") .badge(89) // Create badge with an integer Text("WiFi") .badge("Off") // Create badge with a string }
Output:
Create a badge with a Text view
We can show a badge using the Text
view within the badge()
modifier. This modifier also accepts a Text
view as its content parameter. This Text
view represents the content of the badge, which displays text such as a count or a label.
With this method, we can fully customize the appearance of our badges using various Text view properties such as foregroundColor, font, italic, bold, and string interpolation.
Example
List { Text("Inbox") .badge( Text("69") .foregroundColor(.red) ) Text("Auto-rotate") .badge( Text("Off") ) Text("WiFi") .badge( Text("\(Image(systemName: "wifi"))") ) }
Output:
Leave a Reply