ScottyBlades
ScottyBlades

Reputation: 14073

How to center a second HStack View?

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.

enter image description here

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

Answers (3)

jnpdx
jnpdx

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.

enter image description here

Upvotes: 1

J--
J--

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

J--
J--

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

Related Questions