How do I stretch a View to its parent frame with S

2019-07-31 21:50发布

问题:

Below you see the image and the black square i want to stretch to the red borders.

I have tried the following

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

but result is this:

回答1:

You can use GeometryReader and wrap your ScrollView into it and set content width to the geometry's width size. A GeometryReader:

returns a flexible preferred size to its parent layout.

So your code would be something like below:

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