我正在尝试使用@Published
并@ObservedObject
遵循本文在 2 个视图之间传递数据,但由于某种原因,我无法传递数据,@Published
只是保持初始状态,而不是在单击按钮时更改。
第一个视图ProductList2
导航到 tabView,我正在尝试将数据传递给其中一个 tabView。任何帮助,将不胜感激。
这是我正在创建的ObservableObject
视图@Published
class selectedApplication: ObservableObject {
@Published var selectedApplication = "All"
}
struct ProductList2: View {
@ObservedObject var selectedOption = selectedApplication()
var products: [ProductModel] = productData
var body: some View {
VStack {
HStack {
List{
ForEach(applicationsArray, id: \.self) { item in
Button(action: {
self.selectedOption.selectedApplication = item
}) {
HStack(){
Image(item)
Text(item)
}
}
}
}
}
List{
let matchedItems = products.filter {
product in
let list = product.application
for item in list {
if item == selectedOption.selectedApplication {
return true
}
}
return false
}
ForEach(matchedItems) { item in
NavigationLink(destination: ProductTabView(product: item)) {
ProductListRow(product: item)
}
}
}
}
}
}
这是我试图检索数据的 tabview 视图:
struct ProductTab5View: View {
var product: ProductModel
@ObservedObject private var application = selectedApplication()
var body: some View {
VStack(alignment: .leading){
Text(product.detailTabNames[3])
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0){
ForEach(product.application, id: \.self) { item in
Button(action: {
application.selectedApplication = item
}) {
VStack {
Image(item)
Text(item)
}
}
}
}
}
VStack(alignment: .center){
Text(application.selectedApplication)
}
}
}
}
编辑:
我已经更新了导航链接,@ObservedObject
但仍然无法正常工作:
这是更新后的 ProductList2 NavigationLink:
ForEach(matchedItems) { item in
NavigationLink(destination: ProductTabView(product: item, application: selectedOption.selectedApplication)){
ProductListRow(product: item)
}
}
这是@ObservedObject
在 ProductTab5View 上,我也无法预览工作:
@ObservedObject private var application: selectedApplication
struct ProductTab5View_Previews: PreviewProvider {
static var previews: some View {
ProductTab5View(product: productData[0], application: application)
}
}