I have recently ported an app to Mac Catalyst and I'm trying to configure my app's tool bar to essentially mirror the macOS News and Stocks apps where they have a back button and share button in the toolbar. See below:
Desired Outcome :
This code works when I add it to the AppDelegate but not when I add it to a normal ViewController class.
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
If anyone has any ideas on how to fix or even improve my implementation I will be grateful.
Thanks!
