Problem With The Provided Answers
Since the provided answers work well in various situations, none of them creates the true space-between
spacing behavior similar to CSS, where all elements are equally spaced regardless of the container width.
Using just a plain Spacer
between elements may cause elements and text to be shrunk and truncated in smaller containers when there isn't enough space for both the elements and the Spacers
, as the Spacer
also requires some amount of space.
The results of the provided answers may appear like this:
Solution
However, you can resolve this issue by setting the minimumWidth
for the Spacers
to 0 and assigning a higher layoutPriority
to the desired elements like this:
struct SpaceBetweenView: View {
var body: some View {
HStack(spacing: 0) {
ForEach(0..<6, id: \.self) { item in
if item != 0 {
Spacer()
// Set the minWidth to 0 so the Spacer can shrink to 0 width
// and doesn't block any space required for the Text view below.
.frame(minWidth: 0) // <--
}
Text("Item \(item)")
.lineLimit(1)
.background(Color.green)
// Use a higher layoutPriority for the desired view to prevent it from shrinking
// when there is not enough space in the container
// for both (the Spacers and the elements).
.layoutPriority(1) // <--
}
}
.frame(width: 300, height: 200)
.border(Color.black)
}
}
#Preview {
SpaceBetweenView()
}
By this technique, you can achieve true horizontal space-between
behavior for your views regardless of the container size. The text elements will no longer be truncated due to the use of Spacers
, and will only truncate when there isn't enough space for the elements themselves.
Result
Tested on Xcode 15.2, Swift 5, iOS 16.6