gpt4 book ai didi

swiftui - 不接收场景相位变化

转载 作者:行者123 更新时间:2023-12-03 14:36:50 25 4
gpt4 key购买 nike

我正在尝试执行一些我之前放在我的应用程序委托(delegate)中的代码,例如在进入后台时保存我的托管对象上下文。我把电话拨到 .onChange对于场景阶段,但我什么也没得到。这是一个示例项目:

import SwiftUI

@main
struct PhaseApp: App {
@Environment(\.scenePhase) private var scenePhase

var body: some Scene {
WindowGroup {
Text("Hello, world.")
}
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print("Active")
case .background:
print("Background")
case .inactive:
print("Inactive")
@unknown default: break
}
}
}
}
每当我按主页或点击应用程序时,我希望在模拟器或我的测试设备上获得打印命令,但没有任何 react 。

最佳答案

使用内部场景 Root View (通常为 ContentView )
使用 Xcode 12/iOS 14 进行测试。

struct ContentView: View {
@Environment(\.scenePhase) private var scenePhase
var body: some View {
TestView()
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
print(">> your code is here on scene become active")
case .inactive:
print(">> your code is here on scene become inactive")
case .background:
print(">> your code is here on scene go background")
default:
print(">> do something else in future")
}
}
}
}
backup

关于swiftui - 不接收场景相位变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62840571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com