Pyrettt Pyrettt
Pyrettt Pyrettt

Reputation: 291

Swift UI ScrollView layout behaviour

Does ScrollView in SwiftUI proposes no height for its children.

ScrollView {
    Color.clear
           .frame(idealHeight: 200)
           .background(.blue)
}

will result in enter image description here

As written in frame documentation

The size proposed to this view is the size proposed to the frame, limited by any constraints specified, and with any ideal dimensions specified replacing any corresponding unspecified dimensions in the proposal.

So does it mean scrollView doesn't propose any height?

Upvotes: 0

Views: 59

Answers (1)

Adrien
Adrien

Reputation: 1917

A ScrollView with a vertical axis does not offer a height because its height is potentially infinite. So the child views adopt their idealHeight. Which in the case of a view that normally uses all the height offered, like Color, or Rectangle, corresponds to the magic number 10.

struct SwiftUIView: View {
    @State private var height: CGFloat = 0
    var body: some View {
        ScrollView {
            Rectangle()
                .background(
                    GeometryReader { geo in
                        Color.clear
                            .onAppear {
                                height = geo.size.height
                            }
                    }
                )
        }
        .overlay(Text(height.description), alignment: .bottom)
    }
}

proof

Note that we also find this magic number 10 (putting aside the ScrollView) if we ask the same Rectangle to use its idealHeight, using the modifier .fixedSize

struct SwiftUIView101: View {
    @State private var height: CGFloat = 0
    var body: some View {
        VStack {
            Rectangle()
                .fixedSize()
                .background(
                    GeometryReader { geo in
                        Color.clear
                            .onAppear {
                                height = geo.size.height
                            }
                    }
                )
            Text(height.description)
        }
    }
}

proof 2

Upvotes: 1

Related Questions