2 years ago
#64147

ColomerLu
SwiftUI make scrollview item by item
I need to create a list view with item like a square on a scrollview.
But I need to make the scroll only work to one item to another.
I could see the article allowing to set up this system on a HStack but I can't adapt it on a VStack
This article : https://levelup.gitconnected.com/snap-to-item-scrolling-debccdcbb22f
If someone has an idea to help me in this research?
I join an example of scrollview with the square :
struct ScrollingSnapped: View {
var colors: [Color] = [.blue, .green, .red, .orange, .gray, .brown, .yellow, .purple]
var body: some View {
ScrollView {
VStack(alignment: .trailing, spacing: 30) {
ForEach(0..<colors.count) { index in
colors[index]
.frame(width: 250, height: 250, alignment: .center)
.cornerRadius(10)
}
}
}
}
}
struct ScrollingSnapped_Previews: PreviewProvider {
static var previews: some View {
ScrollingSnapped()
}
}
I tried to work with a ScrollViewReader
that allows to scrollTo
. It works when clicking on a button but I can't get it to work when scrolling :
import SwiftUI
struct ScrollingSnapped: View {
var colors: [Color] = [.blue, .green, .red, .orange, .gray, .brown, .yellow, .purple]
var body: some View {
ScrollViewReader { proxy in
ScrollView {
Button {
proxy.scrollTo(4, anchor: .top)
} label: {
Text("Scroll to square 5")
}
VStack(alignment: .trailing, spacing: 30) {
ForEach(0..<colors.count) { index in
colors[index]
.frame(width: 250, height: 250, alignment: .center)
.cornerRadius(10)
.id(index)
}
}
}
}
}
}
struct ScrollingSnapped_Previews: PreviewProvider {
static var previews: some View {
ScrollingSnapped()
}
}
ios
swift
xcode
swiftui
scrollview
0 Answers
Your Answer