SwiftUI의 프로그래스 뷰
SwiftUI의 프로그래스 뷰
대용량 파일이나 api 통신을 할 때 진행율을 표시해야 할 경우가 있다 이럴때 프로그래스뷰를 사용해서 진행율을 표시할 수 있다 기본적인 프로그래스 뷰도 있지만 사용자 정의 프로그래스 뷰를 생성할 수 있다
Progressview 추가하기
프로그래스 뷰의 기본 값은 원형을 도는 표시가 되며 언제 끝나는지 모르는 불확정적인 프로그래스 뷰를 표시할 때 사용한다
1
2
3
4
5
6
7
8
9
10
11
import SwiftUI
struct ContentView: View {
@State private var progress: Double = 1.0
var body: some View {
VStack {
ProgressView("Task Progress")
}
.padding()
}
}
슬라이더 프로그래스 뷰는 진행율을 일자로 표시할 때 사용한다
1
2
3
4
5
6
7
8
9
10
11
12
13
import SwiftUI
struct ContentView: View {
@State private var progress: Double = 1.0
var body: some View {
VStack {
ProgressView("Task Progress", value: progress, total: 100)
.progressViewStyle(LinearProgressViewStyle())
Slider(value: $progress, in: 0...100)
}
.padding()
}
}
슬라이더는 단순히 값을 변화시킬때 프로그래스 뷰 표시가 변하는것을 표시하기 위해서 넣었다 progress값을 다른곳에 연결해서 사용하면 된다
사용자 정의 프로그래스 뷰
프로그래스뷰는 ProgressViewStyle 프로토콜을 준수하는 구조체를 선언하고 인스턴스를 progressViewStyle() 수정자에 전달해서 변경 할 수 있다
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
import SwiftUI
struct ContentView: View {
@State private var progress: Double = 1.0
var body: some View {
VStack {
ProgressView("Task Progress", value: progress, total: 100)
.progressViewStyle(ShadowProgressViewStyle())
Slider(value: $progress, in: 0...100)
}
.padding()
}
}
struct ShadowProgressViewStyle: ProgressViewStyle {
func makeBody(configuration: Configuration) -> some View {
ProgressView(configuration)
.accentColor(.red)
.shadow(color:Color(red:0,green:0.7,blue:0),
radius:5.0,x:2.0,y:2.0)
.progressViewStyle(LinearProgressViewStyle())
}
}
#Preview {
ContentView()
}
만든 구조체에서 makeBody를 통해서 프로그래스 뷰의 구성 정보를 전달한다
또한 프로그래스 뷰를 반환할 때 모든 타입의 view를 반환할 수 있어서 진행율을 표시한 text뷰 또한 반환 가능하다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct ShadowProgressViewStyle: ProgressViewStyle {
func makeBody(configuration: Configuration) -> some View {
// `VStack`을 사용해 ProgressView와 텍스트를 함께 표시
VStack {
ProgressView(configuration)
.accentColor(.red)
.shadow(color: Color(red: 0, green: 0.7, blue: 0), radius: 5.0, x: 2.0, y: 2.0)
.progressViewStyle(LinearProgressViewStyle())
// 퍼센트를 계산하여 텍스트로 표시
if let fractionCompleted = configuration.fractionCompleted {
let percentage = Int(fractionCompleted * 100)
Text("\(percentage)%")
.font(.subheadline)
.foregroundColor(.gray)
}
}
}
}
This post is licensed under CC BY 4.0 by the author.