Kheldar
Kheldar

Reputation: 5389

Do I get an infinite loop when setting a ScrollView with a Geometry reader up?

I'm trying to figure out the basics of ScrollViews in SwiftUI. I figured if I created a Text with a frame of the width of the screen and .infinite height, which I understood to mean "as large as the available space, e.g. safe area", and dropped it into a ScrollView with another Text companion, I'd get a screen-sized Text that could scroll horizontally to the companion Text.

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            GeometryReader { geometry in
                        VStack {
                            Text("crash me")
                        }
                            .frame(width: geometry.size.width,
                                   height: .infinity,
                                   alignment: .topLeading)
                    }
            Text("crash me")
            
        }
    }
}

If I run this, it just crashes. What's so stupid about it?

Upvotes: 0

Views: 584

Answers (1)

George
George

Reputation: 30461

Instead of:

.frame(height: .infinity)

You should use:

.frame(maxHeight: .infinity)

Setting the exact height to .infinity is not possible, but maxHeight means that the view will stretch its height to the maximum value possible. This would be the size of the screen, or any other limiting factor set by the parent.

Upvotes: 1

Related Questions