14

In SwiftUI, I have a VStack with a Rectangle inside. The rectangle automatically fills the parent VStack, which is great for the width, but I want to make the height equal to the width so it's square. How do I set the aspect ratio to 1:1 or set height = width?

VStack {
  Rectangle()
    .frame(height: ?? )  // I want to make the height equal to width so it's square
  Spacer()

}

LuLuGaGa
  • 13,089
  • 6
  • 49
  • 57
yantronica
  • 353
  • 1
  • 3
  • 12

2 Answers2

31

It's the .aspectRadio() modifier that you need:

public func aspectRatio(_ aspectRatio: CGFloat? = nil,
                        contentMode: ContentMode) -> some View
  • Parameters:

    • aspectRatio: The ratio of width to height to use for the resulting view. Use nil to maintain the current aspect ratio in the resulting view.

    • contentMode: A flag that indicates whether this view fits or fills the parent context.

  • Return Value: A view that constrains this view’s dimensions to the aspect ratio of the given size using contentMode as its scaling algorithm.

If you give it an explicit aspectRatio of 1.0 you can be sure that it will retain its square shape:

VStack {
    Rectangle()
        .aspectRatio(1.0, contentMode: .fit)
    Spacer()
}
shim
  • 9,289
  • 12
  • 69
  • 108
LuLuGaGa
  • 13,089
  • 6
  • 49
  • 57
4

I assume you expect this

enter image description here

VStack {
    Rectangle()
        .aspectRatio(contentMode: .fit)
    Spacer()
}
Asperi
  • 228,894
  • 20
  • 464
  • 690