\n
Here is the code.
\nimport SwiftUI\n\nstruct DaySummariesBarChart: View {\n\n var body: some View {\n HStack {\n Text("Date")\n .font(.footnote)\n Text("Date")\n Spacer()\n }\n }\n}\n\nstruct BarChart_Previews: PreviewProvider {\n static var previews: some View {\n DaySummariesBarChart()\n .previewLayout(.sizeThatFits)\n }\n}\n\n
\n","author":{"@type":"Person","name":"ScottyBlades"},"upvoteCount":0,"answerCount":3,"acceptedAnswer":{"@type":"Answer","text":"This is a pretty clean way to do it:
\nvar body: some View {\n ZStack {\n Text("Date")\n .font(.footnote)\n .frame(maxWidth: .infinity, alignment: .leading)\n Text("Date")\n }\n}\n
\nThe first Text
gets a maxWidth of infinity
, so it takes up the whole space, but is aligned to .leading
.
The second Text
is centered by default in the ZStack
.
Reputation: 14073
I'm having trouble centering that second "Date" Text
within the HStack
. As you can see, in the image, it is a bit farther to the left. I want only the second view to be centered in the HStack. I want the first View to be latched to leading.
Here is the code.
import SwiftUI
struct DaySummariesBarChart: View {
var body: some View {
HStack {
Text("Date")
.font(.footnote)
Text("Date")
Spacer()
}
}
}
struct BarChart_Previews: PreviewProvider {
static var previews: some View {
DaySummariesBarChart()
.previewLayout(.sizeThatFits)
}
}
Upvotes: 0
Views: 283
Reputation: 52625
This is a pretty clean way to do it:
var body: some View {
ZStack {
Text("Date")
.font(.footnote)
.frame(maxWidth: .infinity, alignment: .leading)
Text("Date")
}
}
The first Text
gets a maxWidth of infinity
, so it takes up the whole space, but is aligned to .leading
.
The second Text
is centered by default in the ZStack
.
Upvotes: 1
Reputation: 302
You can use a GeometryReader to make the width of the Views exactly half and therefore center the second one.
struct DaySummariesBarChart: View {
var body: some View {
GeometryReader { geometry in
HStack {
Text("Date")
.font(.footnote)
.frame(width: geometry.size.width / 2)
Text("Date")
.frame(width: geometry.size.width / 2)
}
}
}
}
Upvotes: 0
Reputation: 302
The Spacer() moves the Views to the left. Your problem should be solved by adding another Spacer() on the other side.
struct DaySummariesBarChart: View {
var body: some View {
HStack {
Spacer()
Text("Date")
.font(.footnote)
Text("Date")
Spacer()
}
}
}
Upvotes: 0