Search code examples
iosswiftlistswiftuiscrollview

Scroll to specific section and item in SwiftUI list


I have a List with 12 sections that represent the months of a year and each seach has the number of days of a month as an item. The problem is ScrollViewReader only scrolls the items of the first section. for example, January contains 31 days and it works when I call scroll.scrollTo(23, anchor: .center). How can I make scrollView scroll to a specific section 5 (June) and item 9 (today)?. Here is my code:

let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ,31]

    ScrollViewReader { scroll in 

    List {
        Section("January") {
            ForEach(0..<daysInMonth[0], id:\.self) {
                CalendarRow(calendar: fetchCalendarData(section: 0, index: $0))
            }
        }
.
.
.
// and other sections to December

    }
}

.onAppear {
                withAnimation { scroll.scrollTo(ROW, anchor: .center) }
            }

Solution

  • scrollTo(_:, anchor:) goes to a view with a specific ID. You aren't assigning any IDs to your views, so presumably you're accidentally taking advantage of some default. Make a specific ID for each day in each month (e.g. January-01 ... December-31) and assign that to each calendar row:

    CalendarRow(...).id("June-09")