You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中onChange(of: scenePhase)在iOS14系统下无法触发问题求助

这是iOS 14.x的已知系统Bug,问题出在scenePhase环境值的变化不会向下传递给WindowGroup内的子视图,该问题仅存在于iOS14版本,iOS15及以上系统已修复,和你的代码逻辑无关。

修复方案

  • 方案1:将onChange监听逻辑迁移到Scene层级,兼容所有支持scenePhase的系统版本
import SwiftUI

@main
struct testApp: App {
    
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        // 监听逻辑移到Scene层级
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
            @unknown default:
                print("unknown phase")
            }
        }
    }
}
  • 方案2:如果需要在子视图内监听生命周期,iOS14可通过监听UIKit的生命周期通知实现
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
            .onAppear {
                // 监听进入前台
                NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { _ in
                    print("did become active")
                }
                // 监听进入后台
                NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { _ in
                    print("did enter background")
                }
            }
    }
}

内容的提问来源于stack exchange,提问作者Matsumoto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:27:03