如何使用SwiftUI将视图拉伸到其父框架?

如何使用SwiftUI将视图拉伸到其父框架?,swift,swiftui,Swift,Swiftui,下面是图片和我想要延伸到红色边框的黑色正方形 我试过以下方法 import SwiftUI struct ContentView : View { var body: some View { HStack(spacing: 1) { Rectangle().frame(width:20).foregroundColor(.red).frame(width:20) ScrollView { VS

下面是图片和我想要延伸到红色边框的黑色正方形

我试过以下方法

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
导入快捷界面
结构ContentView:View{
var body:一些观点{
HStack(间距:1){
矩形().frame(宽度:20).foregroundColor(.red).frame(宽度:20)
滚动视图{
VStack{
ForEach(0..您可以使用滚动视图并将其包装到其中,并将内容宽度设置为几何体的宽度大小。A
GeometryReader

将灵活的首选大小返回到其父布局

因此,您的代码如下所示:

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)
}

HStack(间距:1){
矩形().frame(宽度:20).foregroundColor(.red).frame(宽度:20)
GeometryReader{中的几何体
滚动视图{
VStack{
ForEach(0..另一个(不太)丑陋的黑客修复了SwiftUI中的滚动视图宽度:

ScrollView {
    // ...
    Divider().opacity(0)
}

以下内容还将为您提供所需的结果:

HStack(间距:1){
矩形().frame(宽度:20).foregroundColor(.red).frame(宽度:20)
滚动视图{
VStack{

ForEach(0..Related(replicate?):它看起来确实是一个副本..抱歉。(..但这个问题的措辞要简单得多,以演示问题?)这回答了你的问题吗?@Rivera没有。我已经接受了这里有效的答案。另外,在你链接到的那个问题上,这个问题的答案是我的答案,链接到这里的答案。这是建立在你的基础上的吗?也许如果你粘贴完整的代码编辑?如果我在示例中超过了这个,我会在
HStack得到构建错误(间距:1)
@ioscallerPatchtheCode.com抱歉,有一个额外的“}”:]好的,这很有效!!但是为什么呢ヽ(ಠ_ಠ)ノ? 这是修复bug的黑客行为吗?@ioscallerPatchthecode.com更新了我的答案,并提供了更多详细信息。