下面你会看到我想要拉伸(stretch)到红色边框的图像和黑色方块。

我已经尝试了以下

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

但结果是这样的:

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

最佳答案

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

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

10-10 23:26