Created
October 24, 2025 19:54
-
-
Save edwardsanchez/c97b37cd659ddb67d73bff001f6ab308 to your computer and use it in GitHub Desktop.
Horizontal Scrolling with 2 way sync for picker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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