gpt4 book ai didi

SwiftUI:在 ViewModel 中预览数据

转载 作者:行者123 更新时间:2023-12-03 09:22:54 26 4
gpt4 key购买 nike

我从一个从 web 加载数据的 viewModel 加载我的数据。问题:我想设置一些预览示例数据以在预览窗口中包含内容。目前我的预览包含一个空列表,因为我不提供数据。

我怎样才能做到这一点?

struct MovieListView: View {

@ObservedObject var viewModel = MovieViewModel()

var body: some View {
List{
ForEach(viewModel.movies) { movie in
MovieRow(movie: movie)
.listRowInsets(EdgeInsets())
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
MovieListView()
}
}

class MovieViewModel: ObservableObject{

private let provider = NetworkManager()

@Published var movies = [Movie]()

init() {
loadNewMovies()
}

func loadNewMovies(){
provider.getNewMovies(page: 1) {[weak self] movies in
print("\(movies.count) new movies loaded")
self?.movies.removeAll()
self?.movies.append(contentsOf: movies)}
}
}

最佳答案

这是可能的方法(基于 View 模型成员的依赖注入(inject)而不是紧耦合)

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
// create Movie to be previewed inline, say from bundled data
MovieListView(viewModel: MovieViewModel(provider: nil, movies: [Movie(...)]))
}
}

class MovieViewModel: ObservableObject {

private var provider: NetworkManager?

@Published var movies: [Movie]

// same as before by default, but allows to modify if/when needed explicitly
init(provider: NetworkManager? = NetworkManager(), movies: [Movie] = []) {
self.provider = provider
self.movies = movies

loadNewMovies()
}

func loadNewMovies(){
provider?.getNewMovies(page: 1) {[weak self] movies in
print("\(movies.count) new movies loaded")
self?.movies.removeAll()
self?.movies.append(contentsOf: movies)
}
}
}

关于SwiftUI:在 ViewModel 中预览数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60057191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com