SwiftUI:MacOS上的AppDelegate

8

我正在将一个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 {
        ...
    }
}
2个回答

9
macOS 的等价物使用 NS 前缀。
import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {

...

@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

DidFinishLaunching 代理方法则有不同的签名

func applicationDidFinishLaunching(_ aNotification: Notification) [ ...

如果我有一个多平台应用程序,我必须编写两个具有重复功能的AppDelegate类。 - undefined

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)
        }
    }
}

然后,您可以编写应用程序代理:

import AppKit
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    // Whatever you want to write here
}

这对我来说都起作用了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接