I have an HStack with two Texts.
HStack {
Text("Hello")
Text("World")
}
I want Text("Hello") to be on the left side of the page and Text("12") to be on the right side of the page and for both texts to be equidistant from the exact horizontal center of the page. I added a visual for clarification:Visual
I've tried a bunch of different stuff but I haven't found any way to accomplish this task precisely.
CodePudding user response:
I really didn't understand your need but according to your drawing I think you need something like below,
HStack{
Spacer()
Text("Hello")
.background(Color.orange)
Spacer().frame(width: 20)
Text("World")
.background(Color.orange)
Spacer()
}
CodePudding user response:
Here is a way to do it using .overlay
s over clear views in an HStack
with spacing
to define the gap:
struct ContentView: View {
@State private var gap = CGFloat.zero
var body: some View {
ZStack {
// center line
Color.blue.frame(width: 2)
HStack(spacing: gap) {
Color.clear
.overlay {
HStack {
Spacer()
Text("Hello")
}
}
Color.clear
.overlay {
HStack {
Text("World")
Spacer()
}
}
}
}
// slider to adjust the gap
Slider(value: $gap, in: 0...200)
}
}
CodePudding user response:
You can use the alignment argument of the frame modifier.
Spacing argument for the HStack is for the spacing in between the texts.
HStack(spacing: 0) {
Text("Hello, World!")
.frame(maxWidth: .infinity, alignment: .trailing)
Text("Hello, World!")
.frame(maxWidth: .infinity, alignment: .leading)
}