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
}
}
2
Answers
You could try this approach using a
GeometryReader
to force the text to be trailing, such as:The
Spacer
is not working, because it is inside aScrollView
. Views inside aScrollView
are shown at their ideal size and the ideal size of aSpacer
is very small (10 points).To fix, set
.containerRelativeFrame
on theHStack
, after the padding: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: