I wish to create a full screen scrollable view in Swift UI. I am having a problem in getting the views to display full screen after putting them in a scrollview and vertical stack? Any suggestions?
This is how my code looks
struct ContentView : View {
var body: some View {
//var posts = [Post(postColor: .red), Post(postColor: .blue), Post(postColor: .green)]
ScrollView(.vertical, showsIndicators: false) {
VStack {
Post(postColor: .red)
Post(postColor: .blue)
Post(postColor: .green)
}
}
}
}
struct Post : View {
var postColor : Color
var body : some View {
VStack(alignment: .leading) {
HStack {
Text("Name")
.font(.title)
.fontWeight(.heavy)
Spacer()
}
Text("@Username")
.lineLimit(nil)
.font(.body)
Spacer()
}.background(postColor)
}
}
Image This is the output I have after embedding in a scrollview.
You can use GeometryReader
to achieve this:
struct FullScreenViewsInScrollView: View {
var body: some View {
GeometryReader { geometry in
ScrollView {
VStack(spacing: 0) {
Rectangle()
.foregroundColor(.red)
.frame(height: geometry.size.height)
Rectangle()
.foregroundColor(.blue)
.frame(height: geometry.size.height)
Rectangle()
.foregroundColor(.green)
.frame(height: geometry.size.height)
}
}
}
}
}
the result should be (I scrolled down a little in the live preview):