Carles Estevadeordal
Carles Estevadeordal

Reputation: 1229

SwiftUI some view to its root view

I want to trigger the update of a subview in SwiftUI by changing the state of a @State variable, since it does not update alone when I change the Wallet Object since it is defined as EnvironmentObject. The thing is that I have to initialize the view with environmentObject, and it returns Some View, and cannot cast it to WalletView as it should seem that it should.

var walletView =  WalletView().environmentObject(Wallet(cards: reminders))

if walletView = walletView as? WalletView{
    walletView.isPresented = !walletView.isPresented
}

How can I access the WalletView object?

I've tried:

var walletView =  WalletView()
let someWalletView = walletView.environmentObject(Wallet(cards: reminders))

walletView.isPresented = !walletView.isPresented

but the walletView doesn't seem to update. Any clue?

Upvotes: 1

Views: 248

Answers (2)

Carles Estevadeordal
Carles Estevadeordal

Reputation: 1229

I've solved this by changing the variable isPresented to @Binding, and modifying it then triggers an update on the subclass.

Upvotes: 0

Asperi
Asperi

Reputation: 257493

The SwiftUI approach is to change view state inside view, so as far as I understood what your going to do with WalletView it could be achieved like in the following (scratchy):

struct WalletView: View {
   ...
   var body: some View {
      _some_internal_view
         .onAppear { self.isPresented = true }
         .onDisappear { self.isPresented = false }
   }
}

Upvotes: 1

Related Questions