Skip to content

Instantly share code, notes, and snippets.

@Jager-yoo
Created May 14, 2023 14:26
Show Gist options
  • Save Jager-yoo/ca4c20535fec0e46eda75f26ce1c9f86 to your computer and use it in GitHub Desktop.
Save Jager-yoo/ca4c20535fec0e46eda75f26ce1c9f86 to your computer and use it in GitHub Desktop.
programmatic scrolling 실험
import SwiftUI
struct ContentView: View {
private let target: Int = 100 // ⬅️ 이동할 숫자
var body: some View {
ScrollViewReader { proxy in
ScrollView {
ForEach(1..<200) { num in
Text("\(num)")
.font(.title)
.foregroundColor(num == target ? .red : .gray)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(num == target ? .yellow.opacity(0.5) : .clear)
.frame(width: 360)
)
.id(num) // ⬅️ 이동할 대상에 'id' 를 할당한다
}
.frame(maxWidth: .infinity)
}
.overlay(alignment: .bottomTrailing) {
VStack(spacing: 20) {
Button {
withAnimation {
proxy.scrollTo(target, anchor: .top) // ⬅️ anchor 인자를 바꿔가며 실험해보자!
}
} label: {
RoundedRectangle(cornerRadius: 12)
.fill(.green.opacity(0.8))
.frame(width: 100, height: 80)
.overlay {
Text("anchor:\n'top'")
.bold()
.foregroundColor(.white)
}
.padding([.bottom, .trailing], 20)
}
Button {
withAnimation {
proxy.scrollTo(target, anchor: .center)
}
} label: {
RoundedRectangle(cornerRadius: 12)
.fill(.pink.opacity(0.8))
.frame(width: 100, height: 80)
.overlay {
Text("anchor:\n'center'")
.bold()
.foregroundColor(.white)
}
.padding([.bottom, .trailing], 20)
}
Button {
withAnimation {
proxy.scrollTo(target, anchor: .bottom) // ⬅️ 맨 아래로 '끌어당기려' 고 함
}
} label: {
RoundedRectangle(cornerRadius: 12)
.fill(.blue.opacity(0.8))
.frame(width: 100, height: 80)
.overlay {
Text("anchor:\n'bottom'")
.bold()
.foregroundColor(.white)
}
.padding([.bottom, .trailing], 20)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment