I have some code here simply trying to right align/trailing edge align a text view inside an HStack…no matter what I do, it wants to left align/leading edge align. What do I do?
struct RightAlignedScrollView: View {
let text = "12345"
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
Spacer()
Text(text)
.multilineTextAlignment(.trailing)
}
.padding(.trailing, 10) // Adds padding to avoid text sticking to the edge
}
.frame(maxWidth: .infinity, alignment: .trailing)
.background(Color.gray.opacity(0.2)) // Background to visualize the frame
}
}
1
You could try this approach using a GeometryReader
to force the text to be trailing, such as:
struct RightAlignedScrollView: View {
let text = "12345"
var body: some View {
GeometryReader { geom in
ScrollView(.horizontal, showsIndicators: false) {
HStack {
Spacer()
Text(text)
.multilineTextAlignment(.trailing)
}
.padding(.trailing, 10)
.frame(width: geom.size.width, alignment: .trailing)
}
}
.background(Color.gray.opacity(0.2))
}
}
0
The Spacer
is not working, because it is inside a ScrollView
. Views inside a ScrollView
are shown at their ideal size and the ideal size of a Spacer
is very small (10 points).
To fix, set .containerRelativeFrame
on the HStack
, after the padding:
HStack {
Spacer()
Text(text)
.multilineTextAlignment(.trailing)
}
.padding(.trailing, 10)
.containerRelativeFrame(.horizontal, alignment: .trailing) // 👈 HERE
Other suggestions:
-
The
Spacer
can be dropped, since it doesn’t really work. However, this means you will probably want to use.horizontal
padding, instead of just.trailing
. -
Without the
Spacer
, theHStack
only contains theText
, so theHStack
is now redundant. You could drop theHStack
too and apply.containerRelativeFrame
to theText
instead. -
The
.frame
on theScrollView
is also redundant, because theScrollView
automatically uses the full width of the display. -
The initializer that you are using for
ScrollView
is deprecated. To hide the scroll indicators, use the modifier.scrollIndicators
instead.
Here is how the example could be modified:
ScrollView(.horizontal) {
Text(text)
.multilineTextAlignment(.trailing)
.padding(.horizontal, 10)
.containerRelativeFrame(.horizontal, alignment: .trailing)
}
.scrollIndicators(.hidden)
.background(.gray.opacity(0.2))