Swift UI设置使矩形成为正方形

在SwiftUI中,我有一个内部带有矩形的VStack。矩形会自动填充父VStack,这对于宽度非常有用,但是我想使高度等于宽度,因此它是正方形。如何将纵横比设置为1:1或设置height = width?

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

}

chianday 回答:Swift UI设置使矩形成为正方形

您需要的是.aspectRadio()修饰符:

public func aspectRatio(_ aspectRatio: CGFloat? = nil,contentMode: ContentMode) -> some View
  • 参数:
    • aspectRatio:用于结果的宽高比 视图。如果aspectRationil,则结果视图将保持此状态 视图的长宽比。
    • contentMode:一个标志,指示该视图是否适合 填充父上下文。
  • 返回:将此视图的尺寸限制为 aspectRatio,使用contentMode作为缩放算法。

如果您给它一个明确的aspectRatio为1.0,则可以确保它会保持其方形:

VStack {
    Rectangle()
        .aspectRatio(1.0,contentMode: .fit)
    Spacer()
}
,

我想你期望如此

enter image description here

Query<string>
本文链接:https://www.f2er.com/2783353.html

大家都在问