Language/Swift

[SwiftUI] ScrollView

jaewpark 2022. 9. 12. 16:32

ScrollView

: A scrollable view

 

The scroll view displays its content within the scrollable content region. As the user performs platform-appropriate scroll gestures, the scroll view adjusts what portion of the underlying content is visible. ScrollView can scroll horizontally, vertically, or both, but does not provide zooming functionality.

var body: some View {
    ScrollView {
        VStack(alignment: .leading) {
            ForEach(0..<100) {
                Text("Row \($0)")
            }
        }
    }
}
이름 그대로 스크롤이 가능한 뷰로 상하좌우 스크롤이 되지만, 확대는 되지 않습니다.

 


 

ScrollViewProxy

: A proxy value that supports programmatic scrolling of the scrollable views within a view hierarchy.

 

You don’t create instances of ScrollViewProxy directly. Instead, your ScrollViewReader receives an instance of ScrollViewProxy in its content view builder.

 


 

ScrollViewReader

: A view that provides programmatic scrolling, by working with a proxy to scroll to known child views.

 

The scroll view reader’s content view builder receives a ScrollViewProxy instance; you use the proxy’s scrollTo(_:anchor:) to perform scrolling.

 

struct ScrollViewTest: View {
    // MARK: - PROPERTIES

    @Namespace private var topID
    @Namespace private var bottomID
    
    // MARK: - BODY

    var body: some View {
        ScrollViewReader { (proxy: ScrollViewProxy) in
            ScrollView {
                Button("Scroll to Bottom") {
                    withAnimation {
                        proxy.scrollTo(bottomID)
                    }
                }
                .id(topID)
                
                VStack(spacing: 0) {
                    ForEach(0..<256) { i in
                        color(fraction: Double(i) / 256)
                            .frame(height: 20)
                    }
                }
                
                Button("Scroll to Top") {
                    withAnimation {
                        proxy.scrollTo(topID)
                    }
                }
                .id(bottomID)
            }
        }
    }
}

func color(fraction: Double) -> Color {
    Color(red: fraction, green: 1 - fraction, blue: 125)
}

Scroll to Top / Bottom 을 누르게 되면 제일 상/하단으로 스크롤을 제어합니다.

 

var body: some View {
    ScrollViewReader { (proxy: ScrollViewProxy) in
        ScrollView {
            Button("Jump to #127") {
                withAnimation {
                    proxy.scrollTo(127, anchor: .top)
                }
            }
            
            VStack(spacing: 0) {
                ForEach(0..<256) { i in
                    color(fraction: Double(i) / 256)
                        .frame(height: 20)
                        .id(i)
                }
            }
        }
    }
}
각각의 id를 지정하게되면, 127번째로도 이동을 할 수 있습니다.