Skip to content

Instantly share code, notes, and snippets.

@edwardsanchez
Created October 24, 2025 19:54
Show Gist options
  • Select an option

  • Save edwardsanchez/c97b37cd659ddb67d73bff001f6ab308 to your computer and use it in GitHub Desktop.

Select an option

Save edwardsanchez/c97b37cd659ddb67d73bff001f6ab308 to your computer and use it in GitHub Desktop.
Horizontal Scrolling with 2 way sync for picker
import SwiftUI
struct HorizontalScrolling: View {
nonisolated
struct Group: Hashable, Identifiable, Sendable {
let id: Int
}
let groups = (0..<10).map(Group.init)
@State private var scrollPosition: ScrollPosition = .init(idType: Group.self)
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(groups) { group in
Section(
content: {
ForEach(0..<10) { item in
Text("S\(group.id)" + "I\(item)")
.frame(width: 80, height: 160)
.background(Color.red)
}
},
header: {
Text("Group \(group.id)")
}
)
.id(group)
}
}
.scrollTargetLayout()
}
.scrollPosition($scrollPosition, anchor: .leading)
.safeAreaInset(edge: .bottom) {
Picker(
selection: $scrollPosition.stablePickerValue,
content: {
ForEach(groups) { group in
Text("S\(group.id)")
.tag(group, includeOptional: true)
}
},
label: {
Text("Groups")
}
)
.pickerStyle(.segmented)
}
}
}
private extension ScrollPosition {
var stablePickerValue: HorizontalScrolling.Group? {
get { viewID(type: HorizontalScrolling.Group.self) }
set {
scrollTo(id: newValue, anchor: .leading)
}
}
}
#Preview {
HorizontalScrolling()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment