SwiftUI视图-viewDidLoad()?

时间:2019-06-07 14:35:22

标签: ios swift swiftui

尝试在加载视图后加载图像,驱动该视图的模型对象(请参见下面的MovieDetail)具有urlString。因为SwiftUI View元素没有生命周期方法(并且没有视图控制器来驱动事物),什么是最好的处理方式?

我遇到的主要问题是无论我尝试以哪种方式解决问题(绑定对象或使用State变量),我的视图在加载后才具有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)
            }
        }
    }
}

谢谢。

3 个答案:

答案 0 :(得分:12)

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

我认为viewDidLoad()等于在主体关闭中实施。
SwiftUI以viewDidAppear()viewDidDisappear()的形式为我们提供了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!")
        }
    }
}

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

答案 1 :(得分:10)

我希望这会有所帮助。我发现a blogpost谈论在Appear上做导航视图。

想法是您将服务烘焙到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 = []
                }
            }
        }
    }
}

信用:Majid Jabrayilov

答案 2 :(得分:1)

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

  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")
        }
    }
}