我正在将 SwiftUI iOS 应用程序移植到 macOS。它使用 @UIApplicationDelegateAdaptor 属性包装器来绑定(bind) UIApplicationDelegate 类。不幸的是,UIApplicationDelegate 类在 macOS 上不可用,所以我想知道如何绑定(bind)我的自定义 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 {
...
}
}
最佳答案
几乎是一样的,只不过后来用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)
}
}
}
然后你可以这样写你的应用委托(delegate):
import AppKit
import SwiftUI
class AppDelegate: NSObject, NSApplicationDelegate {
// Whatever you want to write here
}
这一切都对我有用。
关于macos - SwiftUI:MacOS 上的 AppDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71291654/