Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Last active September 18, 2023 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanborror/75f57018315ac4c0ed90d323cf634e49 to your computer and use it in GitHub Desktop.
Save nathanborror/75f57018315ac4c0ed90d323cf634e49 to your computer and use it in GitHub Desktop.
Hack for making defaultScrollView work as expected

Problem

The following code results in a view that does what you expect, always shows the content appearing at the bottom of the scroll view. However, if you start with an empty view and populate it with a few buttons, the tap targets for those buttons will be off until you manually scroll the view.

ScrollView {
  LazyVStack {
    Button(action: {}) { Text("Foo") }
    ...
  }
}
.defaultScrollAnchor(.bottom)

Solution (hack)

Add padding to the scroll view so new content starts at the bottom.

GeometryReader { geo in 
  ScrollView {
    LazyVStack {
      Button(action: {}) { Text("Foo") }
      ...
    }
    .padding(.top, geo.size.height)
  }
  .defaultScrollAnchor(.bottom)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment