Organize your User Interfaces with LabeledContent in SwiftUI
SwiftUI offers a wide range of pre-built controls that we can use to create our user interfaces. It is highly recommended to use these controls as they make our work easier and generally ensure the proper functioning of user interfaces across different devices and configurations. One of these components is LabeledContent
.
LabeledContent
allows us to group a label and a view to ensure the information is displayed aligned and to have a clear structure of how we group information in the user interface. These adapt to their container, such as a Form
.
Let’s see an example of how we can use this view:
Form {
LabeledContent("Name") {
Text("John")
}
LabeledContent("Lastname") {
Text("Doe")
}
LabeledContent("Age") {
Text("24")
}
}
This code shows us a form with a standard style for iOS applications. It contains three elements, and we can see how the style used for each one is homogeneous. To create each row, we use LabeledContent
with the constructor that takes a string and a view as parameters.
Moreover, LabeledContent
has other constructors that allow us to use a string for both parameters (label and value) or to use views for both parameters.
For example, we could use LabeledContent
as follows:
Form {
LabeledContent {
Text("A hammer")
} label: {
Label("Tools", systemImage: "hammer")
}
}
In this code, we use LabeledContent
with two views: a Text
and a Label
.
Options to Customize LabeledContent
You can use the .labelsHidden()
modifier to hide the label part that LabeledContent
contains. Let's see what happens if we use this modifier with the previous view:
Form {
LabeledContent("How many?") {
Toggle("One", isOn: $optionOne)
Toggle("Two", isOn: $optionTwo)
}
}
.labelsHidden()
In the following image, we can see on the left how this user interface looks if we don’t use the labelsHidden()
modifier and on the right how it looks if we do use it:
Additionally, you can create your own styles and apply them to LabeledContent
views using labeledContentStyle(_:)
. To do this, you need to create a style conforming to the LabeledContentStyle
protocol.
You can also apply predefined formats to the values you display using LabeledContent
. For example:
Form {
LabeledContent("Progress", value: 54, format: .percent)
LabeledContent("Balance", value: 54.23, format: .number)
LabeledContent("Site", value: URL(string: "https://www.asynclearn.com")!, format: .url)
}
Conclusion
LabeledContent
is a view that allows us to ensure our applications adhere to the user interface standards expected by our users. It is another useful tool to have in your toolkit when creating user interfaces.