skip to Main Content

Is it possible to explicitly set content size of ScrollView in SwiftUI (like we do in UIKit)? I tried setting frame or height of ScrollView to 10000 points but it seems to be ignored.

2

Answers


  1. ScrollView automatically has contentSize equal to all its child view’s sizes. So you can simply add a Spacer and set a frame for it. Changing the scrollView frame by itself won’t have any effect unless you put scrollView inside another View.

    ScrollView {
        Spacer()
            .frame(height: 1000)
            .frame(maxWidth: .infinity)
        ...
    }
    
    Login or Signup to reply.
  2. In iOS 17+ you can use

    .containerRelativeFrame
    

    Here is some sample code.

    ScrollView(.horizontal) {
        LazyHStack(spacing: 10.0) {
            ForEach(0..<5) { item in
                Rectangle()
                    .fill(.purple)
                    .aspectRatio(3.0 / 2.0, contentMode: .fit)
                    .containerRelativeFrame(
                        .horizontal, count: 4, span: 3, spacing: 10.0)
            }
        }
    }
    .safeAreaPadding(.horizontal, 20.0)
    

    I would also recommend watching the related WWDC video.

    https://developer.apple.com/wwdc23/10159

    Prior to iOS 17 you would have to set the size manually or use the default size.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search