How To Scroll List To Specific Item In SwiftUI

The list is a basic view in SwiftUI and since the second version of SwiftUI, it’s easier to scroll to specific items.

The second version of SwiftUI has introduced ScrollViewReader that allows easy scrolling.

Let’s create a simple List with 50 items embedded inside ScrollViewReader.

ScrollViewReader { scrollViewReader in
    
List(1…50, id: \.self) { item in
        
Text(“Item \(item))
    }
}

It doesn’t do anything special yet. However, scrollViewReader has an interesting method .scrollTo that you can use for example tapping on the item.

.onTapGesture(perform: {
    
withAnimation {
        scrollViewReader.
scrollTo(item)
    }
})

There is used withAnimation to make the scroll smooth. When you tap on each item in List then the List will be scrolled to that item.

You can specify where the item you want to scroll should be placed using anchor, for example, .top.

scrollViewReader.scrollTo(item, anchor: .top)

Now, on each item tap, that item will be on the top of List.

It works in the same way as you use it with onReceive using some Publisher.

Let’s create a simple Timer and State property that keeps the current position.

let publisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default).autoconnect()

@State private var currentPosition = 20

Now, inside onReceive increment currentPosition and invoke scroll.

.onReceive(publisher, perform: { _ in
    
currentPosition += 1
    withAnimation {
        scrollViewReader.
scrollTo(currentPosition, anchor: .top)
    }
})

Every second list will scroll to the next item. Instead of a Timer, you can use different Publishers that can publish positions.