Never use Spacers in SwiftUI Stacks
I’ve observed a certain pattern being used, and I’d want to discuss a potential problem it might cause. Let’s investigate it!
Never use Spacers in SwiftUI Stacks
I’ve observed a certain pattern being used, and I’d want to discuss a potential problem it might cause. Let’s investigate it!

This is a widespread structure in various apps and a very common way how to code it in SwiftUI:
HStack(spacing: 12) {
Text(self.text)
Spacer()
Image(systemName: "dog.fill")
}
At first glance, everything seems fine. But once the text starts to overflow, the wrapping leaves a noticeable gap between the text and the trailing icon — even though a fixed value has been set.
Let’s take a closer look by swapping the views out for plain colors:
HStack(spacing: 12) {
Color.blue
Spacer()
Color.red
}
There it is! The gap is exactly twice what it should be. The Stack places its declared spacing around the Spacer as well — even when the Spacer itself contributes no actual width.

So how to fix it? You can either remove the spacing parameter from the stack and use explicit padding to its child views, or IMO more convenient way is to make one of the views stretchable using a .frame modifier and setting its maxWidth attribute to .infinity like so:
HStack(spacing: 12) {
Text(self.text)
.frame(maxWidth: .infinity, alignment: .leading)
Image(systemName: "dog.fill")
}
Let’s compare the behaviour of before and after approaches:

**I personally like the latter solution as it:
- brings simpler code structure**
- has the flexibility to set the alignment of the stretched view (ideal for centering of the view content when needed)
- prevents padding/spacing issues when having optional views in the Stacks
메타데이터
- post_id
- df4d3f6d0a55
- slug
- never-use-spacers-in-swiftui-stacks-df4d3f6d0a55
- url
- https://medium.com/@iacobzanoci/never-use-spacers-in-swiftui-stacks-df4d3f6d0a55
- canonical_url
- https://medium.com/@iacobzanoci/never-use-spacers-in-swiftui-stacks-df4d3f6d0a55
- author_url
- https://medium.com/@iacobzanoci
- status
- ok
- fetched_at
- 2026-07-14 08:54:03