Creating a SwiftUI Scroll-to Feature with ScrollViewReader
Detail Video on Youtube click here to watch !
Introduction:
In this tutorial, we’ll guide you through the process of creating a SwiftUI app that allows users to jump to a specific item in a List
using ScrollViewReader
.
Step 1: Setting up the Project To get started, create a new SwiftUI project in Xcode. You can use the following code snippet as your starting point. This code sets up a simple SwiftUI view with a list and a text field for jumping to specific items.
struct ContentView: View {
@State var inputtext: String = ""
var body: some View {
ScrollViewReader { proxy in
VStack {
List(0..<100, id: \.self) { i in
Text("Item \(i)")
.id(i)
}
HStack {
TextField("Jump to", text: $inputtext)
.padding(.leading, 20)
Button("Jump") {
proxy.scrollTo(Int(inputtext))
}
.padding(20)
}
}
}
}
}
Step 2: Understanding the Code
- We start with a
@State
variable called inputtext` to capture the user's input. - The
ScrollViewReader
is used to make the list scrollable. - The
List
contains 100 items with unique identifiers, and each item is labeled as "Item X," where X is the item's index. - A
TextField
and a "Jump"Button
allow users to specify an item to jump to.
Step 3: Testing the App Build and run your project to see how the scroll-to feature works. Users can enter a number in the text field and press the "Jump" button to scroll to the specified item.
Conclusion:
The magic line of code is proxy.scrollTo(50)
magic which is given by ScrollViewReader