3

I'm trying to implement a ScrollView using SwiftUI that contains an HStack and ForEach() of calendar objects to scroll through back and forth to select a date to mimic below:

enter image description here

The array of dates would be say 30 days in the past of today's date and 30 days in the future. When I initialize the ScrollView, it always starts on the 30th day in the past (Array index 0) but how could I offset the scroll of the ScrollView to where today's date is centered in the view? I've tried using .content.offset(x: offset) but it physically offsets the location of the scroll in the view, not the amount scrolled.

        ScrollView(.horizontal, showsIndicators: false) {

            HStack(alignment: .center, spacing: self.spacing) {

                ForEach(self.dateArray, id: \.self) { date in
                    CalendarObject(date: date)
                }
            }
        }
        .content.offset(x: -self.offset, y: 0)
Kyle Beard
  • 604
  • 5
  • 18
  • 1
    You can use idea from [How to make a SwiftUI List scroll automatically?](https://stackoverflow.com/questions/57258846/how-to-make-a-swiftui-list-scroll-automatically/58708206#58708206) post – Asperi Nov 27 '19 at 05:22
  • That's for that reference! That's definitely a possibility but wow it's a lot of code for such a simple operation. – Kyle Beard Nov 27 '19 at 14:00
  • I wonder if you have found a better solution to this since it's been a year? I'm having the exact issue now. – mota Oct 24 '20 at 15:01
  • The solution is using Xcode 12 with iOS 14 and the latest SwiftUI 2.0 which I believe has the methods needed to set offset now. – Kyle Beard Oct 25 '20 at 18:03

1 Answers1

-1

In apple's example swiftUI Code, they just use padding of cell in ScrollView. Maybe it is an answer from apple.