SwiftUI:MacOS 上的 AppDelegate

G. *_*arc 8 macos swiftui

我正在将 SwiftUI iOS 应用程序移植到 macOS。它使用 @UIApplicationDelegateAdaptor 属性包装器来绑定 UIApplicationDelegate 类。不幸的是,UIApplicationDelegate 类在 macOS 上不可用,所以我想知道如何绑定我的自定义 AppDelegate。

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    ...
    }
}

struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 9

macOS 等效项具有 NS 前缀

import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {

...

@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
Run Code Online (Sandbox Code Playgroud)

并且DidFinishLaunching委托方法具有不同的签名

func applicationDidFinishLaunching(_ aNotification: Notification) [ ...
Run Code Online (Sandbox Code Playgroud)


Mac*_*erT 7

几乎是一样的,但是使用 NS 而不是 UI。我做的和你略有不同:

@main
struct MyApp: App {
    
    // MARK: - Properties
    // Used variables
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @Environment(\.openURL) var openURL
    
    var body: some Scene {
        WindowGroup {
            MainControlView()
        }
        .commands {
            FileMenuCommands(listOfContainers: listOfContainers)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以编写你的应用程序委托,如下所示:

import AppKit
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    // Whatever you want to write here
}
Run Code Online (Sandbox Code Playgroud)

这一切对我有用。