SwiftUI vertical ScrollView springs back up and doesn't show all the views within it

Viewed 268

Im working on a project with a similar layout to this where I have a few views stacked within a VStack and a button on the bottom, all embedded in a scrollview. as you can see in the image the scrollview springs back and doesn't show the button.

enter image description here

var body: some View {
    VStack {
        Rectangle()
            .fill(Color.green)
            .frame(height: 300)
        Spacer()
        ScrollView {
            RectanglesView()
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                Text("Click me")
            }
            .offset(y: 50)
            .frame(width: 300)
            
        }
    }.edgesIgnoringSafeArea(.all)
}

I do believe that the issue is due to the button's offset since it behaves normally if I remove it, but I don't want to lose the placement of the button.

2 Answers

Instead of offset, add padding, like this and within a VStack (slightly amended code below)

    var body: some View {
    ZStack{
        VStack {
            Rectangle()
                .fill(Color.green)
                .frame(height: 300)
            Spacer()
            ScrollView {
                VStack{
                Rectangle()
                    .fill(Color.red)
                    .frame(height: 300)
                Rectangle()
                    .fill(Color.yellow)
                    .frame(height: 300)
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                    Text("Click me")
                    }.padding() //instead of offset
                .frame(width: 300)
                }.frame(alignment: .leading)
                
            }
        }.edgesIgnoringSafeArea(.all)
    }
}

Have you tried moving the Button out of the ScrollView()?

Here is what looks like:

enter image description here

struct ContentView: View {
   var body: some View {
        VStack {
            Rectangle()
                .fill(Color.green)
                .frame(height: 300)
            Spacer()
            ScrollView(.vertical) {
                Rectangle().fill(Color.red).frame(width: 400, height: 200)
                Rectangle().fill(Color.blue).frame(width: 400, height: 200)
                Rectangle().fill(Color.yellow).frame(width: 400, height: 200)
                 Rectangle().fill(Color.green).frame(width: 400, height: 200)
            }
            
            
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                Text("Click me")
                    .font(.headline)
                           }
        }.edgesIgnoringSafeArea(.all)
    }

}
Related