Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- struct
- NotificationCenter
- segue
- 글또
- 화면전환
- Observer
- protocol
- Git
- calendar
- viewlifecycle
- self
- IOS
- SWIFT
- 고차함수
- SWIFTUI
- ScrollView
- error
- uikit
- http
- Switch
- Refresh
- 회고
- apns
- PushNotification
- list
- array
- singleton
- class
- escaping
- mvvm
Archives
- Today
- Total
seong_hye, the developer
SwiftUI) 버튼 활용해 화면 맨 위로 올라오기 본문
📘 SwiftUI - 화면 맨 위로 올라오기
어플을 사용하다보면 스크롤 하다가 버튼을 눌러 화면의 맨 위로 올라오도록 하는 경우를 볼 수 있다
해당 경우를 어떻게 구현했는지 정리해보려 한다.
🔹 기본 개념
- ScrollViewReader: 뷰에 스크롤 위치 조작 기능을 부여할 수 있음
- .id( id 값 ) : 스크롤 목표 위치에 식별자를 붙임
- .scrollTo( id 값 ) : 해당 위치로 스크롤 이동이 가능함
🔹List에 버튼을 통해 위로 올리기
struct ContentView: View {
@State private var showButton = false
let items = Array(1...100)
var body: some View {
ScrollviewReader { proxy in
ZStack(alignment: .bottomTrailing) {
List {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.onAppear { //스크롤 감지 : 아래로 스크롤 시 버튼이 생성되도록
if item > 10 {
withAnimation {
showButton = true
}
}
}
}
}
if showButton {
Button(action: { // 맨 위로 올라가는 버튼
withAnimation {
proxy.scrollTo(1, anchor: .top) // 1 아이디를 가지고 있는 곳으로 가길 원함
showButton = false
}
}) {
Image(systemImage: "arrow.up.circle.fill")
.resizable()
.frame(width: 50, height: 50)
.padding()
.foregroundColor(.blue)
}
}
}
}
}
}
➡️ 결과 화면
🔹ScrollView로 맨 위로 올리기
list를 사용할 수 없는 경우는 scrollView + LazyVStack을 사용하곤 함
이 경우는 어떻게 할 수 있는지 정리
(방식은 거의 동일)
struct ContentView: View {
@State private var showButton = false
let items = Array(1...100)
var body: some View {
ScrollviewReader { proxy in
ZStack(alignment: .bottomTrailing) {
ScrollView {
LazyVStack(alignment: .leading) {
ForEach(items, id: \.self) { item in
Text("Item \(item)")
.padding()
.frame(maxWidth: .infinity, alignment: .center)
.background(.gray)
.cornerRadius(8)
.onAppear { //스크롤 감지 : 아래로 스크롤 시 버튼이 생성되도록
if item > 10 {
withAnimation {
showButton = true
}
}
}
}
}
}
if showButton {
// 위랑 동일
}
}
}
}
}
➡️ 결과 화면
🔹키워드 정리
.id("id 값") // list의 값에서는 (id:\.self)로 정의 | 스크롤 타켓 위치 정의 (맨 위에) |
ScrollViewReader | 뷰의 위치를 제어할 수 있게 함 |
.scrollTo("id 값") | 버튼 클릭 시 해당 위치로 이동 |
withAnimation | 스크롤을 부드럽게 이동 |
showButton | 일정 스크롤 이후에만 벝느 표시되도록 UX 개선 |
🔹함수 활동 요약
목적 | 사용법 |
ScrollView 내 특정 위치로 이동 | ScrollViewReader + .scrollTo(id:) |
맨 위로 이동하기 | .id("id 값") > .scrollTo("id 값") |
버튼 표시 조건 | 스크롤 하단 항목 등장 시 showButton = true |
'IOS > SwiftUI' 카테고리의 다른 글
SwiftUI) View Life Cycle (0) | 2022.10.27 |
---|---|
SwiftUI) App Protocol에 대해 알아보기 (0) | 2022.10.25 |
SwiftUI) Picker & DatePicker 사용하기 (0) | 2022.08.31 |
SwiftUI) 하단 Refresh 추가하기 (0) | 2022.08.24 |
SwiftUI) LazyVGrid & LazyHGrid 알아보기 (0) | 2022.08.23 |
Comments