问题描述
我正在尝试向我的Mac Catalyst应用程序添加一个MenuBar项。
我已经成功地使iPad应用程序在Mac上运行,但是添加MenuBar项却非常困难。
我尝试使用以下两个链接来解决该问题,但是它们没有可供我查看的GitHub存储库,其解释也有所改进。
https://www.highcaffeinecontent.com/blog/20190607-Beyond-the-Checkbox-with-Catalyst-and-AppKit https://developer.apple.com/documentation/xcode/creating_a_mac_version_of_your_ipad_app
现在,我的AppDelegate中包含以下代码:
#if targetEnvironment(macCatalyst)
import AppKit
import Cocoa
#endif
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate {
#if targetEnvironment(macCatalyst)
var popover: NSPopover!
var statusBarItem: NSStatusItem!
#endif
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
#if targetEnvironment(macCatalyst)
// Code to include from Mac.
#endif
#if targetEnvironment(macCatalyst)
let contentView = MenuBarView()
// Create the popover
let popover = NSPopover()
popover.contentSize = NSSize(width: 400,height: 500)
popover.behavior = .transient
popover.contentViewController = NSHostingController(rootView: contentView)
self.popover = popover
// Create the status item
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let button = self.statusBarItem.button {
button.image = NSImage(named: "MenuBar")
button.action = #selector(togglePopover(_:))
}
#endif
return true
}
#if targetEnvironment(macCatalyst)
@objc func togglePopover(_ sender: AnyObject?) {
if let button = self.statusBarItem.button {
if self.popover.isShown {
self.popover.performClose(sender)
} else {
self.popover.show(relativeTo: button.bounds,of: button,preferredEdge: NSRectEdge.minY)
self.popover.contentViewController?.view.window?.becomeKey()
}
}
}
#endif
func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
#if targetEnvironment(macCatalyst)
if let titlebar = windowScene.titlebar {
titlebar.titleVisibility = .hidden
titlebar.toolbar = nil
}
#endif
}
...more code from CoreData
正在显示的错误
我真的是iOS开发的新手,我真的迷失了方向,因此对每一项帮助都非常感激。
编辑
是的,屏幕截图来自AppDelegate。
我正在尝试实现以下内容: https://github.com/AnaghSharma/Ambar-SwiftUI
到目前为止,我看到的每个实现都将其放入AppDelegate中,这就是为什么我也尝试做同样的事情。
解决方法
从您的屏幕截图中可以看出,这就是 Mac套装的AppDelegate。如果是这种情况,则需要删除所有UIKit和#if TARGET_MAC_CATALYAT东西,然后在AppKit中进行所有操作。也就是说,使用NSResponder代替UIResponder等。
对于示例代码而言,这是一个很好的开始:https://github.com/noahsark769/CatalystPlayground
它包括一个AppKit捆绑包和用于加载它的代码。