Simon
Simon

Reputation: 1850

SwiftUI ScrollView too small when content changes

This code:


struct ContentView: View {

    @State var active: Bool = false

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            View2(active: self.$active).onTapGesture {
                self.active.toggle()
            }
        }
    }
}

struct View2: View {

    @Binding var active: Bool

    var body: some View {
        Group {

            ZStack {
                if self.active {
                    Rectangle().frame(width: UIScreen.main.bounds.width/1.2, height: 200).foregroundColor(Color.red)
                }

                Rectangle().frame(width: UIScreen.main.bounds.width/1.5, height: 100).foregroundColor(Color.yellow)
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

When then pressing on the Rectangle. The scrollview appears to be too small. You can now move the rectangle horizontal as well as "scroll" it. You can clearly see that it cuts the new content off with a border that seems to be set with the width of the first item.

How can I make this border/ container go away so that when the size of the content displayed changes it is all visible and only vertical scroll?

enter image description here

enter image description here

Upvotes: 1

Views: 348

Answers (1)

Asperi
Asperi

Reputation: 257503

Here is possible workaround

var body: some View {
    Group {

        ZStack {
            Rectangle().frame(width: UIScreen.main.bounds.width/1.2, height: 200)
                .foregroundColor(self.active ? .red : .clear)    // << here !!

            Rectangle().frame(width: UIScreen.main.bounds.width/1.5, height: 100).foregroundColor(Color.yellow)
        }
    }
}

Upvotes: 1

Related Questions