티스토리 뷰

iOS 개발/SwiftUI

SwiftUI) ScrollView 예제

iDrogba 2022. 1. 30. 22:18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import SwiftUI
 
struct ContentView: View {
    
    @State private var proxy: ScrollViewProxy?
    @State private var indexID: String = "0"
    
    var body: some View{
        VStack{
            
            HStack{
                Text("Insert Index : ")
                TextField("", text: $indexID)
            }.padding()
            
            Button("Scroll To #\(indexID)"){
                withAnimation(.easeInOut(duration: 0.3)) {
                    proxy?.scrollTo(indexID, anchor: .center)
                }
            }
        
            ScrollView{
                ScrollViewReader(content: { proxy in
                    ForEach(0..<50){index in
                        Text("\(index)")
                            .padding()
                            .id(String(index))
                    }
                    .onAppear(perform: {
                        self.proxy = proxy
                    })
                })
            }
            
        }
    }
    
}
 
struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        ContentView()
    }
    
}
cs

 

  • 이동할 위치를 입력하는 TextField(HStack), 이동 Button, ScrollView 세 개로 이루어짐.
  • indexID 변수로 이동할 위치 Index 바인딩.
  • Button.withAnimation() : 애니메이션 효과 설정.
  • ForEach.id(String(index)) : ForEach문에서 생성하는 TextView 각각에게 ID를 할당해줌. String(index)로 할당하여 상단부 TextField와 Button에서 String to Int 변환없이 다룰 수 있게함.

 

'iOS 개발 > SwiftUI' 카테고리의 다른 글

SwiftUI) json networking  (0) 2022.02.15
SwiftUI) @State, @Binding 예제  (0) 2022.01.31
SwiftUI) TextEditor 예제  (0) 2022.01.30
SwiftUI) Toggle Custom 예제  (0) 2022.01.30
SwiftUI) TabView 사용 예제  (0) 2022.01.29
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함