【问题标题】:Swift UI setting making rectangle squareSwift UI设置制作矩形正方形
【发布时间】:2020-01-12 09:05:34
【问题描述】:

在 SwiftUI 中,我有一个 VStack,里面有一个 Rectangle。矩形会自动填充父 VStack,这对于宽度来说非常有用,但我想让高度等于宽度,所以它是方形的。如何将纵横比设置为 1:1 或设置高度 = 宽度?

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

}

【问题讨论】:

    标签: swift swiftui xcode11 vstack


    【解决方案1】:

    这是您需要的 .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()
    }
    

    【讨论】:

      【解决方案2】:

      我猜你期待这个

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

      【讨论】:

      • 我也试过这种方式,没有 1.0,这也有效。
      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 2020-01-28
      • 2014-06-14
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      相关资源
      最近更新 更多