Skip to content

Instantly share code, notes, and snippets.

@mobibob
Created August 27, 2024 14:02
Show Gist options
  • Save mobibob/b1644fcc98191d84ac5afed1eebb1595 to your computer and use it in GitHub Desktop.
Save mobibob/b1644fcc98191d84ac5afed1eebb1595 to your computer and use it in GitHub Desktop.
SwiftUI pattern for scroll-view conditional on macOs and iOs
// Conditional compile for macOs and iOS code.
ScrollViewReader { scrollView in
ScrollView {
List {
ForEach(items, id: \.self) { item in
Text(item)
}
}
.onChange(of: selectedItem) { newValue in
#if os(iOS)
scrollView.scrollTo(newValue, anchor: .center)
#elseif os(macOS)
scrollView.scrollTo(newValue)
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment