Hiding Labels In SwiftUI

Posted in SwiftUI

Updated on October 11th, 2024

⏱ Reading Time: 3 mins

SwiftUI provides a variety of views, with a big number of them being actually actionable controls, including buttons, pickers, the toggle, slider, stepper and more. All controls have readable labels, but some of them display their label out of the area that users can interact with. For these controls specifically, it is possible to hide labels when their appearance is not desirable for various reasons. For instance, they might not fit to the look of the rest of the UI, or the control’s function is clear from the context. Managing that is extremely simple thanks to a not so well-known view modifier, details of which are presented right next.

Hiding labels

Consider the following simple implementation that presents a date picker in compact form:

See that the “Pick a date” label is visible on one side, while the picker button with the date is shown on the other side. We can make the label disappear and keep the actionable element only by applying a view modifier named labelsHidden():

Notice this time that not only the label is missing, but also the essential part of the control has been repositioned to the center of the screen.

It’s quite important to make clear one fact; the above works in views that the label is not within the visual element we interact with. For example, labelsHidden() has no effect in buttons, since the label is an essential part of the button. On the other hand, this view modifier can perfectly work with all pickers and views like the slider, stepper and toggle.

The labelsHidden() modifier has no parameters and used as demonstrated in the previous example. But besides applying it directly to a view, we can also apply it to a container view that contains the kind of views mentioned above. The next VStack, for instance, contains a Toggle and a Stepper view:

We can hide the labels simply by applying the labelsHidden() modifier to the VStack instead of on each individual view:

That’s pretty much all to it around the labelsHidden() view modifier. However, there’s one more important thing to keep in mind; provide label values even if you are planning on hiding them for accessibility reasons. VoiceOver and other assistive technologies will use them in order to make these controls accessible to users.

Conclusion

There is no doubt that the labelsHidden() view modifier is not a common one, but it’s quite effective in cases you need it. In my opinion, it’s one of the underrated APIs in SwiftUI that developers might not be aware of, but it exists for a single job, which it does pretty well. So, were you aware of that view modifier?

Thank you for reading, happy coding!

Stay Up To Date

Subscribe to my newsletter and get notifiied instantly when I post something new on SerialCoder.dev.

    We respect your privacy. Unsubscribe at any time.