gpt4 book ai didi

ios - 当工作表中的 scenePhase 发生变化时触发一个 Action

转载 作者:行者123 更新时间:2023-12-05 03:22:49 25 4
gpt4 key购买 nike

sheet 中的 scenePhase 发生变化时,如何触发 Action ?我尝试了 onChange 修饰符,但当应用进入后台时它不会触发。

import SwiftUI

struct ContentView: View {
var body: some View {
Text("Hello, world!")
.sheet(isPresented: .constant(true), content: SheetView.init)
}
}

struct SheetView: View {
@Environment (\.scenePhase) private var scenePhase
@State private var isFolderLocked = true
var body: some View {
Text("Hello, world!")
.onAppear {
print("view appeared.")
// if folder is locked, authenticate and unlock it
}
.onChange(of: scenePhase) { newValue in
print("scenePhase changed.")
// if scenePhase == .background, lock folder
}
}
}

更新代码:

import SwiftUI

struct ContentView: View {
@Environment (\.scenePhase) private var scenePhase
var body: some View {
Text("Hello, world!")
.sheet(isPresented: .constant(true)) {
SheetView()
.environment(\.scenePhase, scenePhase)
}
}
}

struct SheetView: View {
@Environment (\.scenePhase) private var scenePhase
var body: some View {
NavigationView {
NavigationLink("Show FirstDetailsView") {
FirstDetailsView()
.environment(\.scenePhase, scenePhase)
}
}
}
}

struct FirstDetailsView: View {
@Environment (\.scenePhase) private var scenePhase
var body: some View {
NavigationLink("Show SecondDetailsView") {
SecondDetailsView()
.environment(\.scenePhase, scenePhase)
}
.onChange(of: scenePhase) { _ in
print("scenePhase changed.")
}
}
}

struct SecondDetailsView: View {
@Environment (\.scenePhase) private var scenePhase
var body: some View {
Text("This is SecondDetailsView")
}
}

最佳答案

.sheet 修饰符引入了新的表示,并且环境不会自动复制到那里。我们必须明确地这样做,比如

struct ContentView: View {
@Environment (\.scenePhase) private var scenePhase
var body: some View {
Text("Hello, world!")
.sheet(isPresented: .constant(true)) {
SheetView()
.environment(\.scenePhase, scenePhase) // << here !!
}
}
}

使用 Xcode 13.4/iOS 15.5 测试

关于ios - 当工作表中的 scenePhase 发生变化时触发一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72620039/

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