73

在视图加载后尝试加载图像,驱动视图的模型对象(请参阅下面的 MovieDetail)有一个 urlString。因为 SwiftUIView元素没有生命周期方法(并且没有视图控制器驱动事物),所以处理这个问题的最佳方法是什么?

我遇到的主要问题是无论我尝试以哪种方式解决问题(绑定对象或使用状态变量),我的视图urlString在加载之前都没有...

// movie object
struct Movie: Decodable, Identifiable {

    let id: String
    let title: String
    let year: String
    let type: String
    var posterUrl: String

    private enum CodingKeys: String, CodingKey {
        case id = "imdbID"
        case title = "Title"
        case year = "Year"
        case type = "Type"
        case posterUrl = "Poster"
    }
}
// root content list view that navigates to the detail view
struct ContentView : View {

    var movies: [Movie]

    var body: some View {
        NavigationView {
            List(movies) { movie in
                NavigationButton(destination: MovieDetail(movie: movie)) {
                    MovieRow(movie: movie)
                }
            }
            .navigationBarTitle(Text("Star Wars Movies"))
        }
    }
}
// detail view that needs to make the asynchronous call
struct MovieDetail : View {

    let movie: Movie
    @State var imageObject = BoundImageObject()

    var body: some View {
        HStack(alignment: .top) {
            VStack {
                Image(uiImage: imageObject.image)
                    .scaledToFit()

                Text(movie.title)
                    .font(.subheadline)
            }
        }
    }
}

提前致谢。

4

4 回答 4

67

我希望这是有帮助的。我发现了一篇关于在 onAppear 上为导航视图做一些事情的博文。

想法是您将服务烘焙到 BindableObject 并在您的视图中订阅这些更新。

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<ReposStore, Never>()

    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 = []
                }
            }
        }
    }
}

归功于:马吉德·贾布拉伊洛夫

于 2019-06-07T15:01:37.300 回答
56

我们可以使用视图修饰符来实现这一点。

  1. 创建ViewModifier
struct ViewDidLoadModifier: ViewModifier {

    @State private var didLoad = false
    private let action: (() -> Void)?

    init(perform action: (() -> Void)? = nil) {
        self.action = action
    }

    func body(content: Content) -> some View {
        content.onAppear {
            if didLoad == false {
                didLoad = true
                action?()
            }
        }
    }

}
  1. 创建View扩展:
extension View {

    func onLoad(perform action: (() -> Void)? = nil) -> some View {
        modifier(ViewDidLoadModifier(perform: action))
    }

}
  1. 像这样使用:
struct SomeView: View {
    var body: some View {
        VStack {
            Text("HELLO!")
        }.onLoad {
            print("onLoad")
        }
    }
}
于 2020-10-23T07:41:21.410 回答
22

针对 Xcode 11.2、Swift 5.0 进行了全面更新,

我认为这viewDidLoad()与在 body 闭包中实现相同。
SwiftUI 以viewDidAppear()andviewDidDisappear()的形式为我们提供了与 UIKit 的等价物onAppear()onDisappear()。你可以将任何代码附加到这两个事件上,SwiftUI 会在它们发生时执行它们。

例如,这将创建两个使用onAppear()onDisappear()打印消息的视图,以及在两者之间移动的导航链接:

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView()) {
                    Text("Hello World")
                }
            }
        }.onAppear {
            print("ContentView appeared!")
        }.onDisappear {
            print("ContentView disappeared!")
        }
    }
}

参考:https ://www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear

于 2020-01-09T06:52:36.187 回答
6

我正在使用init()。我认为onApear()不是viewDidLoad(). 因为 onApear 在您的视图出现时被调用。由于您的视图可能会出现多次,因此它与viewDidLoad调用一次的视图相冲突。

想象一下拥有一个TabView. 通过滑动页面 onApear() 被多次调用。然而 viewDidLoad() 只被调用一次。

于 2021-08-18T13:58:58.843 回答