Refreshable modifier

이메일 앱처럼 밑으로 그래드하여 새로고침하는 기능을 사용할 수 있습니다

 

 

애플 공식 문서에 나와있는 예제 코드는 다음과 같습니다

List(mailbox.conversations) { conversation in
    ConversationCell(conversation)
}
.refreshable {
    await mailbox.fetch()
}

 

위에 코드처럼 List로도 사용할 수 있고 ScrollView를 이용한 ForEach로도 사용할 수 있습니다.

NavigationStack {
    ScrollView {
        VStack {
            ForEach(viewModel.items, id: \.self) { item in
                Text(item)
                    .font(.headline)
            }
        }
    }
    .refreshable {
        await viewModel.loadData()
    }
    .navigationTitle("Regreshable")
    .task {
        await viewModel.loadData()
    }
}

 

추가로 await을 사용하여 비동기적 작업이 진행되는 동안에도 ProgressVeiw를 띄울 수 있습니다.

 

 

 

전체 코드

import SwiftUI

final class RefreshableDataService {
    
    func getDate() async throws -> [String] {
        try? await Task.sleep(nanoseconds: 5_000_000_000)
        return ["iOS16", "iOS17", "iOS18"].shuffled()
    }
}


@MainActor
final class RefreshableModifierViewModel: ObservableObject {
    @Published private(set) var items: [String] = []
    let manager = RefreshableDataService()
    
    func loadData() async {
        do {
            items = try await manager.getDate()
        } catch {
            print(error)
        }
    }
}

struct ContentView: View {
    
    @StateObject private var viewModel = RefreshableModifierViewModel()
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack {
                    ForEach(viewModel.items, id: \.self) { item in
                        Text(item)
                            .font(.headline)
                    }
                }
            }
            .refreshable {
                await viewModel.loadData()
            }
            .navigationTitle("Regreshable")
            .task {
                await viewModel.loadData()
            }
        }
    }
}

#Preview {
    ContentView()
}
ytw_developer