【问题标题】:SwiftUI, changing a view from scene(:continueSwiftUI,从场景更改视图(:继续
【发布时间】:2020-12-03 22:37:34
【问题描述】:

在SwiftUI 应用程序中,我面临着新的挑战,希望有人能给我一些提示或指导。到目前为止,我所看到的在应用程序各部分之间进行通信的机制似乎不太适合这里。但这可能是由于我对SwiftUI 的经验仍然有限。

首先是相关代码:

class SceneDelegate {
  ... lot of code irrelevant to the question ...
  func scene(_ scene: UIScene, 
             continue userActivity: NSUserActivity) {
      ... useful things happening for the app ...
      // Now the view should change ... by some mechanism.
      // This is the point of the question.
  }
}

和:

struct ContentView: View {
    ... lot of code irrelevant to the question ...
    var body: some View {
        VStack {
          ... code to draw the view ...
        }
        ... more code to draw the view ...
    }
}

其次,我的问题是:在 scene(:continue ?

我想到了一些想法,在 scene(:continue 函数中做一些会影响视图绘制的事情。

不幸的是,在尝试实现时,我意识到绘制视图的代码是在 scene(:continue 函数之前执行的。因此我需要一些其他机制(通知之类,绑定之类,或 ?? ) 以重绘视图。

有没有好的做法或标准方法来做到这一点?

【问题讨论】:

  • 实现一个根视图(位于您的 ContentView 上方),它显示一些加载状态,直到 .onReceive 或直到某些环境变量发生变化,然后它将呈现 ContentView跨度>

标签: ios swift swiftui uiscenedelegate


【解决方案1】:

在这种情况下使用EnvironmentObject 是合适的

class AppState: ObservableObject
   @Published var someVar: Sometype
}

class SceneDelegate {
  let appState = AppState()

  func scene(_ scene: UIScene, 
             continue userActivity: NSUserActivity) {

     // ... other code 
     appState.someVar = ... // modify
  }
}

  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

     // .. other code
    let contentView = ContentView()
        .environmentObject(appState)
     //
  }
}

struct ContentView: View {
    @EnvironmentObject var appState

    var body: some View {
        VStack {
            // ... other code
            appState.someVar // use here as needed
        }
    }
}

【讨论】:

  • 我正在努力实施您的建议。最后一部分(在 ContentView 中使用 appState.someVar)是最困难的。因为如您所知,如果不让编译器生气,不可能将 if 语句放在不知名的地方(在这种代码中)。我现在正试图弄清楚我可以把它放在哪里让事情顺利进行。
猜你喜欢
  • 1970-01-01
  • 2022-01-20
  • 2021-08-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2019-10-19
  • 2020-03-02
  • 1970-01-01
相关资源
最近更新 更多