Making a SwiftUI List scroll automatically can be useful for various purposes, such as showcasing content or implementing an automatic scrolling feature. To achieve automatic scrolling in a SwiftUI List, you can use the ScrollViewReader
and onAppear
modifiers. Here’s a step-by-step guide on how to do this:
Step 1: Create a SwiftUI List
First, create a SwiftUI List with the items you want to display. For this example, we’ll use a simple List of text items:
import SwiftUI struct AutoScrollListView: View { var body: some View { List(0..<100, id: \.self) { index in Text("Item \(index)") } } }
Step 2: Create a ScrollViewReader
To control the scroll position of the List, you’ll need a ScrollViewReader
. You can wrap your List inside a ScrollViewReader
:
struct AutoScrollListView: View { var body: some View { ScrollViewReader { proxy in List(0..<100, id: \.self) { index in Text("Item \(index)") } } } }
Step 3: Add an onAppear
Modifier
You can use the onAppear
modifier to automatically scroll the List when the view appears. To do this, you need to identify the item you want to scroll to. For example, to scroll to the last item, you can use List.indices
:
struct AutoScrollListView: View { var body: some View { ScrollViewReader { proxy in List(0..<100, id: \.self) { index in Text("Item \(index)") } .onAppear { // Scroll to the last item proxy.scrollTo(99, anchor: .bottom) } } } }
In the above code, proxy.scrollTo(99, anchor: .bottom)
scrolls to the last item with the specified anchor. You can customize this to scroll to a specific item or any other anchor position.
Step 4: Trigger the Scroll
Now, when you navigate to or present the AutoScrollListView
, it will automatically scroll to the specified item. This can create an effect of automatic scrolling through the List.
Keep in mind that the onAppear
modifier will trigger the scroll when the view appears, so you might need to consider when and how you present or navigate to this view to control the timing of the automatic scrolling.