作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当 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/
当 sheet 中的 scenePhase 发生变化时,如何触发 Action ?我尝试了 onChange 修饰符,但当应用进入后台时它不会触发。 import SwiftUI struct Con
我是一名优秀的程序员,十分优秀!