SwiftUI:检查WINDOW(非应用程序)是否已激活(变为前台)的方法

iklwldmw  于 2022-12-10  发布在  Swift
关注(0)|答案(2)|浏览(186)

当我的应用程序成为前台时,我需要在事件上调用一些方法
(我对每个视图都使用ViewModel,所以我不仅可以从视图调用某物)
例如:
1.我的应用程序正在运行;
1.将前台窗口更改为Safari应用程序。
1.将前台窗口更改为我的应用程序-〉调用了某个方法。
使用.onChange(of: scenePhase) -> .active时,此场景不会发生任何情况
所以这些代码对我来说不是解决方案:

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    var body: some View {
        TestView()
            .onChange(of: scenePhase) { phase in
                switch phase {
                    case .active:
                        print("App is active")
                    default:
                        break
                }
            }
    }
}
jecbmhm3

jecbmhm31#

Way 1:

(better)
You can use custom AppDelegate with function applicationDidBecomeActive
main app file:

import SwiftUI

@main
struct FileBoApp: App {
//SOLUTION p1
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate : AppDelegate
//END SOLUTION p1
    
    var body: some Scene {
        /// bla bla bla
    }
}

appDelegate file:

import Foundation
import SwiftUI

//SOLUTION p2
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidBecomeActive(_ notification: Notification) {
       print("FUUUUUUUUUUUU")
    }
}
//END SOLUTION p2

Way 2:

( alternative )

@SceneBuilder var body: some Scene {
        WindowGroup {
            SomeView()
//SOLUTION
                .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { (_) in
                          print("FUUUUUUUUUUUU")
                        }
//END SOLUTION
            
        }
4ioopgfo

4ioopgfo2#

您可以使用环境变量controlActiveState,如下所示:

@Environment(\.controlActiveState) var controlActiveState

相关问题