How to create SwiftUI HStack that adjusts to accommodate the expansion of one of its subviews?

259 views Asked by At

I have a simple horizontal stack comprising three colour bars:

Like this:

When the yellow bar width is magnified via a gesture, I would expect the purple bar to move to the right to accommodate the expanded yellow bar but instead the yellow bar simply expands UNDERNEATH the purple bar (which remains in into original position).

struct ContentView: View {
@GestureState var scale = CGFloat(1)

var body: some View {
    HStack(spacing: 5) {
        Color(.blue)
            .frame(width: 100, height: 60, alignment: .leading)
        Color(.yellow)
            .frame(width: 100, height: 60, alignment: .leading)
            .scaleEffect(x: scale, y: 1.0, anchor: .leading)

            .gesture(MagnificationGesture()
                .updating($scale, body: { (value, scale, trans) in
                    scale = value
                })

            )
        Color(.purple)
            .frame(width: 100, height: 60, alignment: .leading)
    }
}

}

How can I achieve dynamic adjustment of the HStack layout whilst one of its components is expanding?

Many thanks...

Robert

1

There are 1 answers

0
leorider On

you could try this code:

Color(.yellow)
    .frame(width: CGFloat(100) * scale, height: 60, alignment: .leading)
    .gesture(MagnificationGesture()
                .updating($scale, body: { (value, scale, trans) in
                    scale = value
                })
    )