적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

카테고리 없음

[swiftUI] ScrollViewReader proxy scroll to top

hongssup_ 2025. 2. 4. 17:14
반응형

scroll to top 처럼

원하는 곳으로 스크롤 하는 방법

 

리스트에서

그냥 VStack 에서

 

 

 

List 에서 특정 위치로 스크롤

proxy.scrollTo(0, anchor: .top) 이런 식으로 리스트의 특정 index를 id로 설정하면 된다. 

struct ListScroll: View {
    var body: some View {
        ScrollViewReader { proxy in
            VStack(spacing: 12) {
                Button("Scroll to 0") {
                    withAnimation {
                        proxy.scrollTo(0, anchor: .top)
                    }
                }
                
                List {
                    ForEach(0...40, id: \.self) { index in
                        VStack(spacing: 4) {
                            Text("List \(index)")
                        }
                    }
                }
            }
        }
    }
}

 

 

그냥 스크롤 뷰에서 

ScrollViewReader + .scrollTo()

ScrollViewReader를 사용하면 특정 ID로 스크롤 이동이 가능하다

enum ScrollPosition: String {
    case top
    case bottom
}

struct ScrollViewScroll: View {
    var body: some View {
        ScrollViewReader { proxy in
            VStack(spacing: 12) {
                HStack {
                    Button("Scroll to top") {
                        withAnimation {
                            proxy.scrollTo(ScrollPosition.top.rawValue, anchor: .top)
                        }
                    }
                    Button("Scroll to bottom") {
                        withAnimation {
                            proxy.scrollTo(ScrollPosition.bottom.rawValue, anchor: .bottom)
                        }
                    }
                }
                
                ScrollView {
                    Rectangle()
                        .fill(Color.red)
                        .frame(height: 240)
                        .id(ScrollPosition.top.rawValue)
                    
                    Rectangle()
                        .fill(Color.yellow)
                        .frame(height: 240)
                    
                    Rectangle()
                        .fill(Color.blue)
                        .frame(height: 240)
                    
                    Rectangle()
                        .fill(Color.green)
                        .frame(height: 240)
                        .id(ScrollPosition.bottom.rawValue)
                }
            }
        }
    }
}
728x90
반응형