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()
}
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
aspectRatioisnil, 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, usingcontentModeas 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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With