avatarKhoa Pham
# Summary

The provided web content explains how to make a `ScrollView` fit its content size in SwiftUI.

# Abstract

The article addresses a common issue in SwiftUI where a `ScrollView` expands to fill all available space within an `HStack` or `VStack`. To resolve this, the author suggests using a `GeometryReader` to measure the content size of the `ScrollView`. By capturing the content size and applying it as a constraint, the `ScrollView` can be made to adjust its dimensions to fit its content snugly, preventing it from taking up unnecessary space.

# Opinions

- The author implies that using `GeometryReader` as a background for the `ScrollView` content is an effective method to obtain content size measurements.
- The technique described involves asynchronous updates to the state holding the content size, indicating a preference for non-blocking UI operations.
- The use of `DispatchQueue.main.async` suggests that the author prioritizes maintaining a smooth user interface experience by performing UI-related updates on the main thread.
- The author's choice to set the frame of the `ScrollView` based on the measured content size demonstrates a focus on dynamic and flexible UI layouts.

How to fit ScrollView to content in SwiftUI

If we place ScrollView inside HStack or VStack, it takes all remaining space. To fit ScrollView to its content, we need to get its content size and constrain ScrollView size.

Use a GeometryReader as Scrollview content background, and get the local frame

import SwiftUI
struct HSearchBar: View {
    @State
    private var scrollViewContentSize: CGSize = .zero
    var body: some View {
        HStack {
            searchButton
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 12) {
                    ForEach(store.collections) { collection in
                        collectionCell(collection)
                    }
                }
                .background(
                    GeometryReader { geo -> Color in
                        DispatchQueue.main.async {
                            scrollViewContentSize = geo.size
                        }
                        return Color.clear
                    }
                )
            }
            .frame(
                maxWidth: scrollViewContentSize.width
            )
        }
    }
}
Swiftui
Scrollview
Content
Fit
Size
Recommended from ReadMedium
avatarMohit Gupta
ScrollView in SwiftUI

Overview

3 min read