I have the following code:
struct ContentView: View {
@State var isOn: Bool = false
var body: some View {
HStack(alignment: .top) {
Toggle(isOn: $isOn) {
Text("Hello")
}
Text("The quick brown fox jumped over the lazy dog")
Spacer()
Button("Go") {
print("Knock knock.")
}
.padding()
}
.padding()
}
}
Which results in:
How do I vertically align the top line: The quick brown fox
and Go
with desiredly positioned Hello
?
Of course I can manually tune the alignment with hard-coded .offset()
; I have this now in my code. But that’s ugly and will fall apart if I’d change the font size(s) for example. I’m looking for a proper method without hard-code values.
Isn’t this possible with SwiftUI alignment features?
2
Answers
[Updated]
If you want to align vertically then you need to change your Hstack Alignment from .center to .top. From image below you can see toggle Text and Text are align horizontally.
Here is one approach (the Toggle button toggles background colors on/off):
Output (red line is added after, to show the text baselines):
You would probably want to use GeometryReader to calculate the correct offset, rather than using the hard-coded
y: -5.0
Edit — after quick searching for dynamic sizing instead of hard-coded
y: -5.0
Based on info found here: https://stackoverflow.com/a/63050004/6257435
Looks like custom
.alignmentGuide
is what you need: