Back

Wesley de Groot's Blog
LabeledContent in SwiftUI

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")
        }
    }
}

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 {
                    VStack(alignment: .leading) {
                        Text("#025 Pikachu")
                        Text("#149 Dragonite")
                        Text("#249 Lugia")
                        Text("#145 Zapdos")
                        Text("#150 Mewtwo")
                        Text("#132 Ditto")
                    }
                } label: {
                    Text("Team")
                    Text("#1")
                }
            }
        }
    }

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/

x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap