我试图在this article之后使用@Published
和@ObservedObject
在2个视图之间传递数据,但是由于某些原因,我无法传递数据,@Published
一直保持在初始状态下,它是给定的,而不是在单击按钮时更改。
第一个视图ProductList2
导航到一个tabView,我试图将数据传递到其中一个tabViews。任何帮助将不胜感激。
这是我在其中创建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)
}
}
这是ProductTab5View上的@ObservedObject
,我也无法预览:
@ObservedObject private var application: selectedApplication
struct ProductTab5View_Previews: PreviewProvider {
static var previews: some View {
ProductTab5View(product: productData[0], application: application)
}
}
答案 0 :(得分:2)
您正在使用selectedApplication
的两个不同实例:
struct ProductList2: View {
@ObservedObject var selectedOption = selectedApplication()
struct ProductTab5View: View {
...
@ObservedObject private var application = selectedApplication()
您需要在两个视图中使用相同的实例。
struct ProductTab5View: View {
...
@ObservedObject var application: selectedApplication // declare only
// pass the already created instance to the child view
NavigationLink(destination: ProductTabView(product: item, application: selectedOption))