我想通过更改@State变量的状态来触发SwiftUI中子视图的更新,因为在我更改电子钱包对象时,它不会单独更新,因为它被定义为EnvironmentObject。关键是我必须使用environmentObject初始化视图,并且它返回Some View,并且不能像应有的那样将其强制转换为WalletView。

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

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

如何访问WalletView对象?

我试过了:
var walletView =  WalletView()
let someWalletView = walletView.environmentObject(Wallet(cards: reminders))

walletView.isPresented = !walletView.isPresented

但是walletView似乎没有更新。有什么线索吗?

最佳答案

SwiftUI方法是在视图内部更改视图状态,据我所知,您可以使用WalletView来完成此操作,如下所示(临时):

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

10-06 02:54