Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
Cómo mostrar una matriz en otra vista SwiftUI

Estoy tratando de mostrar valores de matriz, que obtengo de la llamada API. Estoy haciendo una solicitud addToCart en una vista y necesito mostrar su resultado en otra vista.

 class Cart: ObservableObject { @Published var data: ShoppingCartContent? @Published var sections: [SectionContent] = [] private var subscriptions = Set<AnyCancellable>() } extension Cart { func addToCart(productId: Int, productQty: Int) { guard let token = UserDefaults.standard.string(forKey: "token") else { return } NetworkManager.addProductToCart(token: token, productId: productId, productQty: productQty) .sink( receiveCompletion: { completion in switch completion { case .finished: print("finished") case .failure(let error): print("AddToCart error", error) } }, receiveValue: { value in print("Success:", value.success) print("Data:", value.data) self.data = value.data self.sections = value.data.sections print("Sections:", self.sections) }) .store(in: &subscriptions) }}

Obtengo datos de la API, los guardo en las secciones var @Published, pero no puedo mostrarlos en otra vista, la impresión muestra que es nulo.

 struct ShoppingView: View { @EnvironmentObject var viewModel: Cart var body: some View { ScrollView { VStack(alignment: .leading) { HStack { Text("Delivery:") .foregroundColor(Color.textFieldGrayColor) ForEach(viewModel.sections, id: \.self) { section in ForEach(section.items, id: \.self) { product in Text(product.product_name) } } } }.onAppear { print("My cart arr:", cartViewModel.data?.sections) } } }

PS ShoppingView: es una de las pestañas que agregué (environmentObject) en MainView

 @EnvironmentObject var viewModel: Cart ShoppingView().environmentObject(viewModel)

También traté de acceder a la matriz con @ObservedObject var viewModel = Cart() pero también muestra una matriz vacía.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Cuando va a inyectar el modelo de vista, debe crear una instancia

Reemplazar

 @EnvironmentObject var viewModel: Cart ShoppingView().environmentObject(viewModel)

con

 ShoppingView().environmentObject(Cart())

El contenedor de propiedades @EnvironmentObject solo es necesario si hereda el objeto.

over 4 years ago · Santiago Trujillo Report

0

No recomiendo usar ShoppingView().environmentObject(Cart()) : esto creará una nueva instancia de Cart cada vez que se llame a la vista. Terminarás recreando el contenido de tus variables cada vez.

Lo que propongo es reemplazar esta llamada en su código original en MainView :

@EnvironmentObject var viewModel: Cart

con:

@StateObject var viewModel = Cart()

Esto creará un StateObject en MainView que se pasará a ShoppingView a través del entorno. Dependiendo de sus necesidades, también let viewModel = Cart() funcione.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!