gpt4 book ai didi

ios - 如何将测试数据添加到PreviewProvider

转载 作者:行者123 更新时间:2023-12-01 19:29:25 31 4
gpt4 key购买 nike

我是iOS/Swift和MVVM架构的新手,想知道如何将测试数据发送到SwiftUI预览。 (通过API调用从ViewModel接收实际数据)
我要添加的测试数据:

test data = [(name: "Test1", price: "18.00-21.00"), (name: "Test2", price: "8.00-11.00"), (name: "Test3", price: "10.00")]
我的看法:
struct TodayView: View {

@ObservedObject var viewModel: ViewModel

var body: some View {
NavigationView {

List(viewModel.results, id: \.self) { item in

Text(item.name)
.font(.subheadline)
Text(item.price ?? "NIL")
.font(.headline)

}
.listStyle(InsetGroupedListStyle())
.navigationBarTitle(Text("\(viewModel.titleDate)"))

}
}
}

struct TodayView_Previews: PreviewProvider {

static var previews: some View {
// Add Test Data here? How to pass it into TodayView?
TodayView(viewModel: ViewModel())
}
}
我的 View 模型(我同时向 View 发送日期和实际数据):
class ViewModel: ObservableObject {

// Title Date
@Published var titleDate: String = ""

let dateLong = Date()

func createDate() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "E, MMM d"
return formatter.string(from: Date())
}

init(){
self.results = [Model.Calendar]()
titleDate = self.createDate()
loadData()
}


func loadData() {

// API Call

}

// Actual Data received from API call
@Published var results: [Model.Calendar]


}

我的模特:
struct Model {

struct Calendar: Codable, Hashable {
var name: String
var price: String
}

}

最佳答案

您可以尝试以下操作:

struct TodayView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = ViewModel()
viewModel.results = <your_test_data>
return TodayView(viewModel: viewModel)
}
}
另外,您可能需要从 loadData()中删除 init(在ViewModel中),因此您的测试数据不会被覆盖。

关于ios - 如何将测试数据添加到PreviewProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63997052/

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