SwiftUI:MacOS 上的 AppDelegate
SwiftUI: AppDelegate on MacOS
我正在将 SwiftUI iOS 应用移植到 macOS。它使用 @UIApplicationDelegateAdaptor 属性 包装器绑定 UIApplicationDelegate class。不幸的是,UIApplicationDelegate class 在 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 {
...
}
}
对应的 macOS 具有 NS 前缀
import AppKit
class AppDelegate: NSObject, NSApplicationDelegate {
...
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
并且 DidFinishLaunching
委托方法具有不同的签名
func applicationDidFinishLaunching(_ aNotification: Notification) [ ...
差不多,不过后来用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
}
这一切都对我有用。
我正在将 SwiftUI iOS 应用移植到 macOS。它使用 @UIApplicationDelegateAdaptor 属性 包装器绑定 UIApplicationDelegate class。不幸的是,UIApplicationDelegate class 在 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 {
...
}
}
对应的 macOS 具有 NS 前缀
import AppKit
class AppDelegate: NSObject, NSApplicationDelegate {
...
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
并且 DidFinishLaunching
委托方法具有不同的签名
func applicationDidFinishLaunching(_ aNotification: Notification) [ ...
差不多,不过后来用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
}
这一切都对我有用。