Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a view between Spacers always at the center in an HStack?

Tags:

ios

swift

swiftui

What I would like to achieve. regardless the width of text width at both side the button should always at the center of the HStack.

enter image description here

HStack {
    Text("Foooooooo")
    Spacer(minLength: 5)
    Button(action: { }) {
        Text("Bar")
    }
    Spacer()
    Text("Baz")
}
.font(.system(size: 16, weight: .heavy, design: .rounded))
.padding()

enter image description here

I also tried to use GeometryReader and set frame size for each Text and Button in the view however there are two problems,

  1. The view returned by GeometryReader would occupies the entire view the parent offers to it instead of the actual intrinsic content size, the space only enough for Text, Spacer and Button
  2. String inside the first Text could not be left align so does the string inside the last Text couldn't be right aligned
like image 906
X.Creates Avatar asked Sep 05 '20 15:09

X.Creates


Video Answer


1 Answers

Here is possible approach for your case. Demo prepared & tested with Xcode 12 / iOS 14

demo

    HStack {
        Spacer()
            .overlay(Text("Foooooooo"), alignment: .leading)

        Button(action: { }) {
            Text("Bar")
        }

        Spacer()
            .overlay(Text("Baz"), alignment: .trailing)
    }
    .font(.system(size: 16, weight: .heavy, design: .rounded))
    .padding()

backup

like image 142
Asperi Avatar answered Sep 18 '22 13:09

Asperi