leebaek

[SwiftUI] ScrollView | 스크롤뷰 본문

개발/Swift

[SwiftUI] ScrollView | 스크롤뷰

leebaek 2023. 11. 8. 19:01

■ScrollView 

□ ScrollViewReader🔗

□ ScrollViewProxy🔗


■ScrollView 

: 스크롤 가능한 뷰

struct ScrollView<Content> where Content : View

 

> 초기값

- 수직축으로 설정됨

- 막대기 바가 보이게 설정됨

init(Axis.Set, showsIndicators: Bool, content: () -> Content)

init(
    _ axes: Axis.Set = .vertical, // 수직축
    showsIndicators: Bool = true, // 막대기 보이게
    @ViewBuilder content: () -> Content
)

스크롤 위치 제어 | Axis.Set

- 가로, 세로 방향 설정  가능 ( 확대, 축소 기능은 없음 )

// [.vertical]
// [.horizontal]
// [.vertical, .horizontal]

ScrollView([.vertical])
ScrollView([.horizontal])
ScrollView([.vertical,.horizontal])

 

> 처음 스크롤 되는 위치 설정

.defaultScrollAnchor()

.center // 중간에서 시작
.bottom // 수직축 아래에서 시작

 

예시 )

ScrollView([.horizontal, .vertical]) {
    // initially centered content
}
.defaultScrollAnchor(.center)

스크롤 바 제어 | showIndicators

- 스크롤 바 보이게, 안 보이게 설정 가능

// showsIndicators: <Bool>
// showsIndicators: true
// showsIndicators: false

ScrollView(showsIndicators: true)
ScrollView(showsIndicators: false)

ex. 수평 방향 스크롤 뷰 / 중간부터 시작 / 스크롤 바 제거

import SwiftUI

struct ContentView: View {

    var body: some View {
        ScrollView([.horizontal],showsIndicators: false){
            HStack {
                ForEach(0..<100) {
                    Text("Row \($0)")
                }
            }
        }
        .defaultScrollAnchor(.center)
    }
}

#Preview {
    ContentView()
}