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

标签 swift swiftui xcode11 vstack

在 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 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.


如果你给它一个明确的 aspectRatio从 1.0 开始,您可以确定它将保留其方形:
VStack {
    Rectangle()
        .aspectRatio(1.0, contentMode: .fit)
    Spacer()
}

关于Swift UI 设置使矩形变为正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59702380/

相关文章:

ios - GooglePlacePicker 不通过 cocoa pod 安装

ios - 拖到 View 顶部时,UILongPressGestureRecognizer 在表格 View 中崩溃 - SWIFT

swift - 如何根据位置更改 UIPickerView 标题文本颜色

swift - 设置状态栏和导航栏颜色相同

swift - 从选择器 SwiftUI 中取消选择项目

ios - 我在 SwiftUI 中创建了一个自定义选项卡栏,但是当我选择一个选项卡时,它会完全重新加载 View 。我该如何防止这种情况

swiftui - 如何使用顶部的 ScrollView 使背景中的 Button 可点击?

ios - Xcode 11 : Safe Area code implementation using Objective-C not working

ios - Xcode 11 向后兼容性 : "UIWindowScene is only available in iOS 13 or newer"

ios - 使用Xcode 11将SPM下载的包保存到项目GIT中