ios - 如何将 NSToolBarDelegate 添加到 ViewController

标签 ios swift nstoolbar mac-catalyst

我最近将一个应用程序移植到 Mac Catalyst,我正在尝试配置我的应用程序的工具栏,以从本质上反射(reflect) macOS 新闻和股票应用程序,它们在工具栏中有一个后退按钮和共享按钮。见下文:

期望的结果:

enter image description here

这段代码在我将它添加到 AppDelegate 时有效,但在我将它添加到普通 ViewController 类时无效。

class ViewController: UIViewController {

override func viewDidLoad() {

        super.viewDidLoad()

        #if targetEnvironment(macCatalyst)

        UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.forEach { windowScene in

            if let titlebar = windowScene.titlebar {
                let toolbar = NSToolbar(identifier: "testToolbar")

                titlebar.toolbar = toolbar
                toolbar.delegate = self
                titlebar.titleVisibility = .hidden

            }

        }

        #endif

    }

}

#if targetEnvironment(macCatalyst)

private let SettingsIdentifier = NSToolbarItem.Identifier(rawValue: "SettingsButton")
private let TitleIdentifier = NSToolbarItem.Identifier(rawValue: "Title")
private let NavigationIdentifier = NSToolbarItem.Identifier(rawValue: "BackButton")


extension ViewController: NSToolbarDelegate {

    func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {

            if (itemIdentifier == NavigationIdentifier) {

                let barButton = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .done, target: self, action: #selector(test))
                let button = NSToolbarItem(itemIdentifier: itemIdentifier, barButtonItem: barButton)

                return button

            }

            if (itemIdentifier == SettingsIdentifier) {

                let barButton = UIBarButtonItem(image: UIImage(systemName: "ellipsis.circle"), style: .done, target: self, action: #selector(test))
                let button = NSToolbarItem(itemIdentifier: itemIdentifier, barButtonItem: barButton)

                return button

            }

            if (itemIdentifier == TitleIdentifier) {

                let barButton = UIBarButtonItem(title: "My App", style: .plain, target: self, action: nil)
                let button = NSToolbarItem(itemIdentifier: itemIdentifier, barButtonItem: barButton)

                return button

            }

            return nil

        }

        func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {

            return [NavigationIdentifier, NSToolbarItem.Identifier.flexibleSpace, TitleIdentifier, NSToolbarItem.Identifier.flexibleSpace, SettingsIdentifier]

        }

        func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {

            return toolbarDefaultItemIdentifiers(toolbar)

        }

        @objc func test(){

            print("test")

        }

}
#endif


如果有人对如何修复甚至改进我的实现有任何想法,我将不胜感激。

谢谢!

最佳答案

我没有测试您的示例代码 - 所以我认为尝试在 ViewController 中初始化工具栏是行不通的。坦率地说,这并不奇怪,因为根据 Apple 的说法,mac 风格的工具栏应该在应用程序初始化期间添加——最好是在您的 SceneDelegate 类中。正如 Apple 在其 tutorial on how to add a toolbar to a MacCatalyst app 中所述,此示例应用程序在 SceneDelegate 类中管理其主窗口,您将在此处创建工具栏并将其添加到标题栏(教程摘录)。这似乎是 Apple 的要求,很可能与时间和应用程序生命周期有关。

一旦您在应用程序初始化期间添加了工具栏(在 AppDelegate 或 SceneDelegate 中),您就可以稍后在 View Controller 中获取它。例如,您可以根据情况启用或禁用某些工具栏按钮。这是一种方法:

class ToolbarDelegate: NSObject {
    #if targetEnvironment(macCatalyst)
    //do this if you want to manipulate the toolbar through your delegate
    //*** OPTIONAL ***
    weak var mainToolbar: NSToolbar?
    #endif
}

#if targetEnvironment(macCatalyst)
extension ToolbarDelegate: NSToolbarDelegate {
   //perform your ToolbarDelegate configuration
   ...
   ...
   //example function that shows how you can directly manipulate the toolbar via your ToolbarDelegate
   func disableToolbarItem(itemIdentifier: NSToolbar.ItemIdentifier) {
      mainToolbar?.items.first(where: { $0.itemIdentifier == itemIdentifier})?.isEnabled = false
   }
}
#endif

在您的 SceneDelegate 中执行此操作:

//first configure the tool bar in your SceneDelegate as explained in the tutorial above
//cross posting the most relevant parts for convenience, refer to the tutorial for more info
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    ...
    var toolbarDelegate = ToolbarDelegate()
    ...
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        ...
        ...
        #if targetEnvironment(macCatalyst)
        guard let windowScene = scene as? UIWindowScene else { return }
    
        let toolbar = NSToolbar(identifier: "main")
        toolbar.delegate = toolbarDelegate
        toolbar.displayMode = .iconOnly

        //also pass the toolbar reference to your ToolbarDelegate
        //to be able to control it directly
        //*** OPTIONAL ***
        toolbarDelegate.mainToolbar = toolbar
        
    
        if let titlebar = windowScene.titlebar {
            titlebar.toolbar = toolbar
            titlebar.toolbarStyle = .automatic
        }
    #endif
    }
}

然后将其添加到您的 ViewController 中,以便能够访问您的 ToolbarDelegate 并按照您认为合适的方式对其进行操作。

class MyViewController: UIViewController {
    ...
    ...
    var toolbarDelegate: ToolbarDelegate? {
        //notice, this approach only works if your app only has one scene
        //if your app supports multiple scenes, modify this code as necessary
        let scene = UIApplication.shared.connectedScenes.first
        if let sd: SceneDelegate = (scene?.delegate as? SceneDelegate) {
            return sd.toolbarDelegate
        } else {
            return nil
        }
    }

    override func viewDidLoad() {
         super.viewDidLoad()
         
         //disables side bar button (if you had it)
         toolbarDelegate?.disableToolbarItem(NSToolbarItem.Identifier.toggleSidebar)
    }
}

关于ios - 如何将 NSToolBarDelegate 添加到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60836309/

相关文章:

ios - 在 UICollectionView 上放置一个按钮并保持滚动

ios - XCUITest 和 UIActivityViewController

iOS swift ImagePickerController : Improving Edit Mode

ios - 回调函数不重新加载数据库

swift - makeFirstResponder 并不总是触发

cocoa - 如何像evernote一样实现NSToolbarItem动画

ios - 带数组 iOS 的 JSON 字符串

ios - 强制异步任务按顺序运行

swift - 在 iOS 9.0 中通过 WhatsApp 分享

macos - NSToolbarItem: "Make sure this toolbar item has a valid frame/min/max size"?