如何使用 SwiftUI 将视图拉伸到其父框架?
How do I stretch a View to its parent frame with SwiftUI?
下面是图像和我想拉伸到红色边框的黑色方块。
我试过以下方法
import SwiftUI
struct ContentView : View {
var body: some View {
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
}
Rectangle().foregroundColor(.red).frame(width:20)
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View { ContentView() }
}
#endif
但结果是这样的:
您可以使用 GeometryReader 并将 ScrollView 包裹到其中,并将内容宽度设置为几何图形的宽度大小。 A GeometryReader
:
returns a flexible preferred size to its parent layout.
因此您的代码将如下所示:
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
GeometryReader { geometry in
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
.frame(width: geometry.size.width)
}
}
Rectangle().foregroundColor(.red).frame(width:20)
}
在 SwiftUI 中修复 ScrollView
s 宽度的另一个(不那么)丑陋的 hack:
ScrollView {
// ...
Divider().opacity(0)
}
以下也会为您提供您正在寻找的结果:
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minHeight: 50)
}
}
}
Rectangle().foregroundColor(.red).frame(width:20)
}
下面是图像和我想拉伸到红色边框的黑色方块。
我试过以下方法
import SwiftUI
struct ContentView : View {
var body: some View {
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
}
Rectangle().foregroundColor(.red).frame(width:20)
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View { ContentView() }
}
#endif
但结果是这样的:
您可以使用 GeometryReader 并将 ScrollView 包裹到其中,并将内容宽度设置为几何图形的宽度大小。 A GeometryReader
:
returns a flexible preferred size to its parent layout.
因此您的代码将如下所示:
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
GeometryReader { geometry in
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minWidth: 50, maxWidth: .infinity, minHeight: 50, maxHeight: 50)
}
}.relativeWidth(1)
.frame(width: geometry.size.width)
}
}
Rectangle().foregroundColor(.red).frame(width:20)
}
在 SwiftUI 中修复 ScrollView
s 宽度的另一个(不那么)丑陋的 hack:
ScrollView {
// ...
Divider().opacity(0)
}
以下也会为您提供您正在寻找的结果:
HStack(spacing: 1) {
Rectangle().frame(width:20).foregroundColor(.red).frame(width:20)
ScrollView {
VStack {
ForEach(0..<5) { index in
Rectangle().frame(minHeight: 50)
}
}
}
Rectangle().foregroundColor(.red).frame(width:20)
}