navigationLink初始化所有视图

时间:2019-12-04 19:04:31

标签: swift swiftui

我有一个称为源视图的根视图。它从newsapi.org获取所有新闻来源:

struct SourcesView: View {
    @ObservedObject var model = SourcesListViewModel()

    var body: some View {
        ActivityIndicatorView(isShowing: $model.loading) {
            NavigationView {
                List(self.model.sources) { source in
                    VStack(alignment: .center) {
                        NavigationLink(destination: ArticlesView(source: source.name)) {
                            Text(source.name)

                            Text(source.description)
                                .foregroundColor(.secondary)
                                .lineLimit(3)
                        }

                    }
                    .navigationBarTitle(Text("News sources"), displayMode: .inline)
                }
            }
        }
    }
}

现在,我想获取该新闻源发布的所有文章。在UIKit中,didSelectRow会知道被窃听的单元格,并通过其新闻来源名称来获取其文章。但是,进入第二个视图时不会获取新闻报道,就好像未调用初始化方法一样。通过调试,我可以看到所有文章都是在应用程序加载时获取的(源视图是根视图)

struct ArticlesView: View {

    @ObservedObject var model : ArticlesListViewModel
    init(source: String) {
        model = ArticlesListViewModel.init(source: source)
    }

    var body: some View {
        ActivityIndicatorView(isShowing: $model.loading) {
                NavigationView {
                    List(self.model.articles) { article in
                        VStack(alignment: .center) {
                            Text(article.title)

                            Text(article.description)
                                .foregroundColor(.secondary)
                                .lineLimit(3)
                        }
                        .navigationBarTitle(Text("News sources"), displayMode: .inline)
                    }
                }
            }
        }
}
import UIKit
import Combine

class ArticlesListViewModel: ObservableObject {

    init(source: String) {
        fetchArticles(source: source)
    }

    @Published var articles = [ArticlesViewModel]()
    @Published var loading: Bool = true
    func fetchArticles(source: String) {
        loading = true
        NetworkManager.shared.getSourceArticles(selectedSource: source) { (articles) in
            self.articles = articles.map(ArticlesViewModel.init)
            self.loading = false
        }
    }
}

虽然这是一个关于另一个主题的问题,但这可能是有用的,它与我正在使用的应用程序相同:Displaying activity indicator while loading async request in SwiftUI

0 个答案:

没有答案