Make more with SwiftUI’s Label
With SwiftUI 2 Apple added Labels to Swift. Labels combine images and text together, that look good together, scale and have the right frame. Especially when using Labels in a List, you have a big advantage, that the text is always on the same vertical line, independent of the width of the icon. Labels look great yet, but you can make much more out of them.
Alignment
By default, the label content is aligned like this:
This alignment is perfect for lists or large buttons, but sometimes a more compact design can be better. To achieve that, we can create a custom ListStyle
, that can be called via .labelStyle(CustomLabelStyle))
.
The view is made by the makeBody()
function. We can access the icon
and the title
through the configuration
parameter.
Different labels
But you cannot only make Labels
with just Text
and an Image
, but with custom views. The syntax is slightly other, but still very easy and comprehensive.
And the result looks gorgeous. You can also create labels only with text or only with images.
Settings like Labels
Now with Labels you can recreate list rows, similar to the Settings app, easier and better looking than ever. To create this type of Label structures, just put a Label
in the function and modify the title
and the icon
. You can also add input parameters (here color
and size
) to the structure, to customize the Label
even more.
I recreated a simple Settings clone with Labels
inside a List
. It looks good, but not exactly like it should look like.
So you can simply add add the .labelStyle
to your Labels
, select the color, and that’s it! The @ScaledMetric
value is necessary, so that the icon’s background scales based on the dynamic text settings.
Conclusion
SwiftUI’s Label
is great. You have a great base structure, that already fits many use cases. And with that you can expand the Label into more complex, beautiful connections of text and imagery.