DEV Community

Wesley de Groot
Wesley de Groot

Posted on • Originally published at wesleydegroot.nl on

LabeledContent in SwiftUI

As developers, we often need to display a value alongside a label, and manually arranging this can be difficult.

But LabeledContent, a powerful and versatile view that simplifies this common UI pattern.

What Is LabeledContent?

At its core, LabeledContent is a straightforward view that combines a label and content.

It's like a dynamic duo that works together seamlessly.

Let's dive into how it works and explore some practical examples.

Basic Usage

The basic usage of LabeledContent involves providing a label and a corresponding value.

Here's a simple example:

struct ContentView: View {
    var body: some View {
        Form {
            LabeledContent("Label", value: "Content")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In the example below we use different ways to create some LabeledContent:

struct ContentView: View {
    var body: some View {
        Form {
            Section {
                // Version 1: String label & String value
                LabeledContent("Pikachu", value: "#25")

                // Version 2: String label & formatted value
                LabeledContent("Pikachu", value: 25, format: .number)

                // Version 3: String label & any View as value
                LabeledContent("Region") {
                    Image(systemName: "globe.europe.africa.fill")
                    Text("Kanto")
                }

                // Version 4: Any View as value & any View as a label
                LabeledContent {
                    Text("#025 Pikachu")
                    Text("#149 Dragonite")
                    Text("#249 Lugia")
                    Text("#145 Zapdos")
                    Text("#150 Mewtwo")
                    Text("#132 Ditto")
                } label: {
                    Text("Team")
                    Text("#1")
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Download the Swift Playground here

Conclusion

In summary, LabeledContent is a powerful tool for creating well-organized and visually appealing UIs.

Whether you're displaying simple strings or complex views, it streamlines the process and adheres to design guidelines.

Resources:

https://developer.apple.com/documentation/swiftui/labeledcontent/

Top comments (0)