在 SwiftUI 中,我有一个 VStack,里面有一个 Rectangle。矩形会自动填充父 VStack,这对宽度很好,但我想让高度等于宽度,所以它是方形的。如何将纵横比设置为 1:1 或设置高度 = 宽度?
VStack {
Rectangle()
.frame(height: ?? ) // I want to make the height equal to width so it's square
Spacer()
}
最佳答案
这是您需要的 .aspectRadio() 修饰符:
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
isnil
, 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
, usingcontentMode
as its scaling algorithm.
如果你给它一个明确的
aspectRatio
从 1.0 开始,您可以确定它将保留其方形:VStack {
Rectangle()
.aspectRatio(1.0, contentMode: .fit)
Spacer()
}
关于Swift UI 设置使矩形变为正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702380/