SwiftUI View - viewDidLoad()?

前端 未结 3 710
忘了有多久
忘了有多久 2021-01-30 10:35

Trying to load an image after the view loads, the model object driving the view (see MovieDetail below) has a urlString. Because a SwiftUI View element has no life

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 11:15

    I hope this is helpful. I found a blogpost that talks about doing stuff onAppear for a navigation view.

    Idea would be that you bake your service into a BindableObject and subscribe to those updates in your view.

    struct SearchView : View {
        @State private var query: String = "Swift"
        @EnvironmentObject var repoStore: ReposStore
    
        var body: some View {
            NavigationView {
                List {
                    TextField($query, placeholder: Text("type something..."), onCommit: fetch)
                    ForEach(repoStore.repos) { repo in
                        RepoRow(repo: repo)
                    }
                }.navigationBarTitle(Text("Search"))
            }.onAppear(perform: fetch)
        }
    
        private func fetch() {
            repoStore.fetch(matching: query)
        }
    }
    
    import SwiftUI
    import Combine
    
    class ReposStore: BindableObject {
        var repos: [Repo] = [] {
            didSet {
                didChange.send(self)
            }
        }
    
        var didChange = PassthroughSubject()
    
        let service: GithubService
        init(service: GithubService) {
            self.service = service
        }
    
        func fetch(matching query: String) {
            service.search(matching: query) { [weak self] result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let repos): self?.repos = repos
                    case .failure: self?.repos = []
                    }
                }
            }
        }
    }
    

    Credit to: Majid Jabrayilov

提交回复
热议问题