Swift UI 设置使矩形变成正方形
Swift UI setting making rectangle square
在 SwiftUI 中,我有一个 VStack,里面有一个 Rectangle。矩形会自动填充父 VStack,这对宽度来说非常有用,但我想让高度等于宽度,所以它是正方形的。如何将宽高比设置为 1:1 或设置高度 = 宽度?
VStack {
Rectangle()
.frame(height: ?? ) // I want to make the height equal to width so it's square
Spacer()
}
我假设你期待这个
VStack {
Rectangle()
.aspectRatio(contentMode: .fit)
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()
}
在 SwiftUI 中,我有一个 VStack,里面有一个 Rectangle。矩形会自动填充父 VStack,这对宽度来说非常有用,但我想让高度等于宽度,所以它是正方形的。如何将宽高比设置为 1:1 或设置高度 = 宽度?
VStack {
Rectangle()
.frame(height: ?? ) // I want to make the height equal to width so it's square
Spacer()
}
我假设你期待这个
VStack {
Rectangle()
.aspectRatio(contentMode: .fit)
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()
}