gpt4 book ai didi

swift - 如何使用 SwiftUI 将 View 拉伸(stretch)到其父框架?

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:12 26 4
gpt4 key购买 nike

下面是图像和我想拉伸(stretch)到红色边框的黑色方 block 。

我试过以下方法

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

但结果是这样的:

enter image description here

最佳答案

您可以使用 GeometryReader并将您的 ScrollView 包装到其中并将内容宽度设置为几何的宽度大小。一个 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)
}

关于swift - 如何使用 SwiftUI 将 View 拉伸(stretch)到其父框架?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56630578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com