你好! 我想在我的操作程序中顯示進度。我是 swift 和 swiftui 的新手。請幫助...這是具有一種異步方法的模型:
class CountriesViewModel : ObservableObject {
@Published var countries: [String] = [String]()
@Published var isFetching: Bool = false
@MainActor
func fetch() async {
countries.removeAll()
isFetching = true
countries.append("Country 1")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 2")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 3")
Thread.sleep(forTimeInterval: 1)
isFetching = false
}
}
和ContentView:
struct ContentView: View {
@StateObject var countriesVM = CountriesViewModel()
var body: some View {
ZStack {
if (countriesVM.isFetching) {
ProgressView("Fetching...")
}
else {
List {
ForEach(countriesVM.countries, id: \.self) { country in
Text(country)
}
}
.task {
await countriesVM.fetch()
}
.refreshable {
Task {
await countriesVM.fetch()
}
}
}
}
}
}
不顯示進度。我究竟做錯了什么?
uj5u.com熱心網友回復:
你可以試試這個簡單的方法:
struct ContentView: View {
@StateObject var countriesVM = CountriesViewModel()
var body: some View {
ZStack {
if (countriesVM.isFetching) {
ProgressView("Fetching...")
}
else {
List {
ForEach(countriesVM.countries, id: \.self) { country in
Text(country)
}
}
.refreshable {
Task {
await countriesVM.fetch()
}
}
}
}
.task { // <-- here
await countriesVM.fetch()
}
}
class CountriesViewModel : ObservableObject {
@Published var countries: [String] = [String]()
@Published var isFetching: Bool = true // <-- here
@MainActor
func fetch() async {
countries.removeAll()
isFetching = true
countries.append("Country 1")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 2")
Thread.sleep(forTimeInterval: 1)
countries.append("Country 3")
Thread.sleep(forTimeInterval: 1)
isFetching = false
}
}
}
EDIT-1:包括一個重繪 資料的按鈕。
struct ContentView: View {
@StateObject var countriesVM = CountriesViewModel()
var body: some View {
ZStack {
if countriesVM.isFetching {
ProgressView("Fetching...")
}
else {
VStack {
Button("refresh", action: {
Task { await countriesVM.fetch() }
}).buttonStyle(.bordered)
List {
ForEach(countriesVM.countries, id: \.self) { country in
Text(country)
}
}
.refreshable {
await countriesVM.fetch()
}
}
}
}
.task {
await countriesVM.fetch()
}
}
class CountriesViewModel : ObservableObject {
@Published var countries: [String] = [String]()
@Published var isFetching: Bool = false
@MainActor
func fetch() async {
countries.removeAll()
isFetching = true
// representative background async process
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() 2) {
// eventualy, updates on the main thread for the UI to use
DispatchQueue.main.async {
self.countries.append("Country 1")
self.countries.append("Country 2")
self.countries.append("Country 3")
self.isFetching = false
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477779.html
