Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UI setting making rectangle square

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()

}

like image 375
yantronica Avatar asked Jan 12 '20 09:01

yantronica


Video Answer


1 Answers

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. If aspectRatio is nil, the resulting view maintains this view's aspect ratio.
    • contentMode: A flag indicating whether this view should fit or fill the parent context.
  • Returns: A view that constrains this view's dimensions to aspectRatio, 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()
}
like image 162
LuLuGaGa Avatar answered Nov 11 '22 02:11

LuLuGaGa