Skip to content

SwiftUI: ScrollViewReader

In the recent WWDC 2020, Apple introduced an ScrollViewReader. This is one of the feature that a lot of us are looking forward to due to the lack of support in scrolling in the previous SwiftUI.

With ScrollViewReader, you will now be able to scroll to any of the row with the use of index.

A view whose child is defined as a function of a ScrollViewProxy targeting the scrollable views within the child.

Apple Documentation

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 12+
  • Only supports iOS 14+

Getting Started With ScrollViewReader

To begin, you will need to embed ScrollViewReader within ScrollView. Here you will use images from SF Symbols where the first version was first introduced in WWDC 2019 and the subsequent version in WWDC 2020. It’s a great tool by Apple where you could find a lot of useful icons but it mainly only support iOS 13+. In order for it support iOS 13+, there is a workaround which is to export it.

Anyway, let’s not get distracted with SF Symbols and focus on ScrollViewReader. The idea is to have a button on top of the scroll view with about 50 images.

ScrollView {
    ScrollViewReader { value in
        // 1
        Button("Jump to 30") {
            value.scrollTo(30, anchor: .top)
        }
        // 2
        ForEach(1..<51) { index in
            Image(systemName: "\(index).square")
                .font(.largeTitle)
                .frame(height: 70)
                .id(index)
        }
    }
}
  1. This is the button that will appear on the list. By clicking on this, you will be redirected to the row.
  2. Images are created using a forEach with numbers.

Your device should look like below with images and a button.

Clicking on the button will lead you to the index 30.

It really depends on how you would like your index to be shown and you can tweak it by replacing the anchor with a different UnitPoint.

value.scrollTo(30, anchor: .top)

It’s probably good to know the frame of the ScrollView so you know what is happening when different anchors are applied such as trailing or leading.

.zero

.center

.leading

.trailing

.bottom

.topLeading

You can even try topTrailing but you get the idea.

.bottomTrailing

You can even try .bottomLeading but you get the idea.

Where to go From Here

If you feel like you are ready to take on more challenges, feel free to check out some other tutorials that we have created:

Published inSwiftUI

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *