作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个基本 View ,显示从 API 获取数据的列表。我想在从 API 检索数据时实现事件指示器。在MVC中,我们可以使用委托(delegate)和协议(protocol),让 View Controller 继承协议(protocol),在模型完成获取数据后,我们调用委托(delegate)来告诉 View Controller 数据已完成检索(现在隐藏事件指示器等) .)。如何在 SwiftUI 和它的 MVVM 风格中实现类似的事情?
我尝试从这个问题中实现一个事件指示器,我只是不知道如何以及何时停止它:Activity indicator in SwiftUI
My SourcesViewModel(它从 newsapi.org 获取新闻文章来源)
import UIKit
class SourcesViewModel: Identifiable {
let id = UUID()
let source: Sources
init(source: Sources) {
self.source = source
}
var name: String {
return self.source.sourceName
}
var description: String {
return self.source.sourceDescription
}
}
我的 SourcesListViewModel:
import Combine
class SourcesListViewModel: ObservableObject {
init() {
fetchSources()
}
@Published var sources = [SourcesViewModel]()
private func fetchSources() {
NetworkManager.shared.getSourceData { (sources) in
self.sources = sources.map(SourcesViewModel.init)
}
}
}
最后,我的 SourcesView:
import SwiftUI
struct SourcesView: View {
@ObservedObject var model = SourcesListViewModel()
var body: some View {
ActivityIndicatorView(isShowing: .constant(true)) {
NavigationView {
List(self.model.sources) { source in
VStack(alignment: .center) {
Text(source.name)
Text(source.description)
.foregroundColor(.secondary)
.lineLimit(3)
}
.navigationBarTitle(Text("Sources"), displayMode: .inline)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
SourcesView()
}
}
结果:
最佳答案
您的 View 模型应该具有加载状态,如下所示
@Published var loading = false
private func fetchSources() {
self.loading = true
NetworkManager.shared.getSourceData { (sources) in
self.sources = sources.map(SourcesViewModel.init)
self.loading = false
}
}
并且事件指示器应该绑定(bind)到它,例如
ActivityIndicatorView(isShowing: $model.loading) {
关于ios - 在 SwiftUI 中加载异步请求时显示事件指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957327/
我正在开发一个需要能够平均三个数字的 Facebook 应用程序。但是,它总是返回 0 作为答案。这是我的代码: $y = 100; $n = 250; $m = 300; $number = ($y
我只是无法弄清楚这一点,也找不到任何对我来说有意义的类似问题。我的问题:我从数据库中提取记录,并在我的网页上以每个面板 12 条的倍数显示它们。因此,我需要知道有多少个面板可以使用 JavaScrip
我是一名优秀的程序员,十分优秀!